I am trying to write some code that saves the contents of a C++ class in a file. So, I am experimenting with some C and C++ i/o code, but I am stuck in some things...
Lets say I have the following code:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using std::vector;
using std::string;
using std::cout;
struct TestStruct{
string alpha;
string beta;
vector<string> gamma;
};
struct TestStruct2 {
char alpha[32];
char beta[32];
}
int main (int argc, char* argv[]) {
TestStruct *kkk = new TestStruct;
kkk->beta = "hello world!";
kkk->alpha = "hello again!";
kkk->gamma.push_back("hello third");
kkk->gamma.push_back("hello fourth!!!");
FILE *fp = fopen("myfile.soul","wb");
fwrite(kkk,sizeof(TestStruct),1,fp);
fclose(fp);
free(kkk);
TestStruct *lll = new TestStruct;
fp = fopen("myfile.soul","rb");
fread(lll,sizeof(TestStruct),1,fp);
fclose(fp);
cout << lll->gamma[1];
free(lll);
return 0;
}
The error I get when I run this code is:
SoulFramework(1211) malloc: *** Deallocation of a pointer not malloced: 0x3007d0; This could be a double free(), or free() called with the middle of an allocated block; Try setting environment variable MallocHelp to see tools to help debug
SoulFramework(1211) malloc: *** Deallocation of a pointer not malloced: 0x300790; This could be a double free(), or free() called with the middle of an allocated block; Try setting environment variable MallocHelp to see tools to help debug
However, if I use character arrays or something like integers in the struct, the code works just fine.
1)Why? Does that have something to do with classes like std::string and vector that are dynamic?
2)If I definitely want to use those classes with standard C i/o what should I do?
3)If I decide to use C++ i/o, what can I do to store the elements of a class like a vector<customStruct> inside a file? The contents of the customStruct could be integers, floats, or std::strings.
EDIT:
To make myself clear: I have a class, that occupies some memory. Is there any way to save this memory piece into a (binary?) file and then load it the same way? I suppose the file would be unreadable by a text editor, this way.