View Single Post
Old Jul 13th, 2007, 12:10 PM   #1
Soulstorm
Hobbyist Programmer
 
Soulstorm's Avatar
 
Join Date: Jan 2006
Location: Menidi, Athens, Greece
Posts: 239
Rep Power: 3 Soulstorm is on a distinguished road
Stadard C i/o problems with C++ classes

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:

cpp Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <fstream>
  5.  
  6. using std::vector;
  7. using std::string;
  8. using std::cout;
  9.  
  10. struct TestStruct{
  11. string alpha;
  12. string beta;
  13. vector<string> gamma;
  14. };
  15.  
  16. struct TestStruct2 {
  17. char alpha[32];
  18. char beta[32];
  19. }
  20.  
  21. int main (int argc, char* argv[]) {
  22.  
  23. TestStruct *kkk = new TestStruct;
  24. kkk->beta = "hello world!";
  25. kkk->alpha = "hello again!";
  26. kkk->gamma.push_back("hello third");
  27. kkk->gamma.push_back("hello fourth!!!");
  28.  
  29. FILE *fp = fopen("myfile.soul","wb");
  30.  
  31. fwrite(kkk,sizeof(TestStruct),1,fp);
  32. fclose(fp);
  33. free(kkk);
  34.  
  35. TestStruct *lll = new TestStruct;
  36.  
  37. fp = fopen("myfile.soul","rb");
  38. fread(lll,sizeof(TestStruct),1,fp);
  39.  
  40. fclose(fp);
  41. cout << lll->gamma[1];
  42. free(lll);
  43.  
  44. return 0;
  45. }

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.
__________________
Project::Soulstorm (personal homepage)

Last edited by Soulstorm; Jul 13th, 2007 at 12:27 PM.
Soulstorm is offline   Reply With Quote