Segmentation Error when saving file

I have been working a while with saving and retrieve structs, and I still have not got it to work. I get Segmentation fault sh "${SHFILE} . I have search this error, and it has something to do with memory, but I have no idea what, since I am a beginner with saving and retrieving files. The project runs fine, and the error stated above outputs into my console window as text.

Here are my two structs:

1
2
3
4
5
6
7
8
9
10
struct checkbook {
    char id[50];
    double value[50];
};

struct fbook {
    double initial;
    int counter;
    checkbook book;
};


Here is how I save and retrieve my structs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void saveCheckbook (string file, checkbook checkbook, double initial, int counter) {
    
    string path = "C:\\Users\\Ashwin\\Google Drive\\C++\\Checkbook\\" +  file;
    fbook save;
    save.counter = counter;
    save.initial = initial;
    save.book = checkbook;
    char *filep;
    strcpy(filep, path.c_str());
    ofstream outfile (filep, ios::binary | ios::out);
    outfile.write((char*)&save, sizeof(save)); // sizeof can take a type
    outfile.close();
    
}

fbook openCheckbook (string file) {
    
    fbook book;
    string path = "C:\\Users\\Ashwin\\Google Drive\\C++\\Checkbook\\" +  file;
    char *filep;
    strcpy(filep, path.c_str());
    ifstream infile (filep, ios::binary | ios::in);
    infile.seekg (0, infile.end);
    int length = infile.tellg();
    infile.seekg (0, infile.beg);
    infile.read((char*)&book, length);
    infile.close();
    
    return book;
}


Any idea what is wrong?
Last edited on
1
2
    char *filep;                  // undeterminate value
    strcpy(filep, path.c_str()); // <-- BOOM !!! 


filep's value is undeterminate and attempting to dereference or use it might cause segfault.

You wont really need to do this, you can simply use :
1
2
3
4
5
6
7
8
9
10
    fbook save;

    save.counter = counter;
    save.initial = initial;
    save.book = checkbook;

    ofstream outfile (path.c_str(), ios::binary | ios::out); // i think u can simply use path in C++11
    
    outfile.write((char*)&save, sizeof(save)); // sizeof can take a type
    outfile.close(); // <--destructor of ofstream automatically does this 
Topic archived. No new replies allowed.