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.
[CODE=cpp]
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
struct Test
{
int x;
char y;
char * z;
Test() {z = new char[4]; z = "abc";}
~Test() {delete [] z;}
};
int main(int argc, char* argv[])
{
ofstream out;
out.open("l.tst ", ios::out | ios::binary);
char * buffer = new char[256];
Test t;
t.x = 80;
t.y = 's';
memcpy(buffer, &t, sizeof(Test));
out.write(buffe r, sizeof(Test));
out.close();
ifstream in;
in.open("l.tst" , ios::in | ios::binary);
char * inbuf = new char[256];
in.read(inbuf, sizeof(Test));
Test * t2 = new Test;
memcpy(t2, inbuf, sizeof(Test));
in.close();
//Use t2 for something.
cout << t2->x << " " << t2->y << " " << t2->z << endl;
return 0;
}
[/CODE]
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.
[CODE=cpp]
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
struct Test
{
int x;
char y;
char * z;
Test() {z = new char[4]; z = "abc";}
~Test() {delete [] z;}
};
int main(int argc, char* argv[])
{
ofstream out;
out.open("l.tst ", ios::out | ios::binary);
char * buffer = new char[256];
Test t;
t.x = 80;
t.y = 's';
memcpy(buffer, &t, sizeof(Test));
out.write(buffe r, sizeof(Test));
out.close();
ifstream in;
in.open("l.tst" , ios::in | ios::binary);
char * inbuf = new char[256];
in.read(inbuf, sizeof(Test));
Test * t2 = new Test;
memcpy(t2, inbuf, sizeof(Test));
in.close();
//Use t2 for something.
cout << t2->x << " " << t2->y << " " << t2->z << endl;
return 0;
}
[/CODE]
Comment