memory problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DumRat
    New Member
    • Mar 2007
    • 93

    memory problem

    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]
    Last edited by AdrianH; Jun 2 '07, 01:01 PM. Reason: Please use [code=cpp][/code] tags to improve readability.
  • Savage
    Recognized Expert Top Contributor
    • Feb 2007
    • 1759

    #2
    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

    Comment

    Working...