By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,918 Members | 2,225 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,918 IT Pros & Developers. It's quick & easy.

memory problem

P: 93
Hi,
I want to intialise values in my program by reading from a binary file. I thought of doing it in the fllowing way. But it produces a assertion failure when the program returns. I traced the error to the destructor of the Test structure. When I remove z from the structure it works fine. Can anyone tell me what's the problem here? And is there a better way of doing my initializations from a binary? Thanx.

Expand|Select|Wrap|Line Numbers
  1.  
  2. #include "stdafx.h"
  3. #include <iostream>
  4. #include <fstream>
  5.  
  6. using namespace std;
  7.  
  8. struct Test
  9. {
  10.     int x;
  11.     char y;
  12.     char * z;
  13.  
  14.     Test() {z = new char[4]; z = "abc";}
  15.     ~Test() {delete [] z;}
  16. };
  17.  
  18. int main(int argc, char* argv[])
  19. {
  20.     ofstream out;
  21.     out.open("l.tst", ios::out | ios::binary);
  22.  
  23.     char * buffer = new char[256];
  24.  
  25.     Test t;
  26.     t.x = 80;
  27.     t.y = 's';
  28.  
  29.     memcpy(buffer, &t, sizeof(Test));
  30.  
  31.     out.write(buffer, sizeof(Test));
  32.     out.close();
  33.  
  34.     ifstream in;
  35.     in.open("l.tst", ios::in | ios::binary);
  36.  
  37.     char * inbuf = new char[256];
  38.  
  39.     in.read(inbuf, sizeof(Test));
  40.  
  41.     Test * t2 = new Test;
  42.  
  43.     memcpy(t2, inbuf, sizeof(Test));
  44.     in.close();
  45.  
  46.     //Use t2 for something.
  47.         cout << t2->x << " " << t2->y << " " << t2->z << endl; 
  48.  
  49.     return 0;
  50. }
  51.  
  52.  
  53.  
  54.  
Jun 2 '07 #1
Share this Question
Share on Google+
1 Reply


Savage
Expert 100+
P: 1,764
This is not correct:

Test() {z = new char[4]; z = "abc";}

this is what causes a problem,change it to strcpy(z,"abc") and it shall work.

:D

Savage
Jun 2 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.