Weird Problem

Hi Guys,

Code Snippet 1 with malloc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using namespace std;

struct Et {

int i;
string s;
};

int main() {

Et o;
char da[2048];
memset(da, NULL, sizeof(da));
o.i = 10;
o.s = "hello";
memcpy(da, &o, sizeof(o));

Et *p = (Et *) malloc (sizeof(da));
memcpy(p, da, sizeof(da));
cout<<p->i<<"    "<<p->s<<endl;

free( p);

return 0;

}


Code Snippet 2 with new
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using namespace std;

struct Et {

int i;
string s;
};

int main() {

Et o;
char da[2048];
memset(da, NULL, sizeof(da));
o.i = 10;
o.s = "hello";
memcpy(da, &o, sizeof(o));

Et *p = new Et;
memcpy(p, da, sizeof(da));
cout<<p->i<<"    "<<p->s<<endl;

delete p;

return 0;

 };


What I don't understand is, why does 1st code snippet (where I am using malloc) work and why does 2nd code snippet (where I am using new and delete) throws error saying that double free.

Maybe it's because delete invokes the destructor whereas free doesn't.
You shouldn't mix memcpy and memset with new/delete unless you really know what you are doing!
You can't copy Et with memcpy(). It contains a std::string, which contains pointers to memory from the heap.

As Et is C++ object, you can't create one with malloc(). You've only got a raw block of data that's large enough to hold an Et.
@onur
Yeah man, I am pretty sure why I am using that thing.

@kbw
Could you please elaborate it more because if I am not wrong, malloc just allocates memory, I don't know what it has to do with C++ object? Could you please explain it

Thanks
1
2
3
4
5
6
Et o;
char da[2048];
memset(da, NULL, sizeof(da));
o.i = 10;
o.s = "hello";
memcpy(da, &o, sizeof(o));

This memcpy is just plain bad. o is an Et, which has a string, which in turn has pointers to stuff. You cannot treat an object like this. You have to use a C++ copy method

1
2
3
Et *p = (Et *) malloc (sizeof(da));
memcpy(p, da, sizeof(da));
cout<<p->i<<"    "<<p->s<<endl;

This again is bad. You've created a 2K block of memory, copied some stuff into it and gone on to treat it as an object Et.

Casting in C is routine, but it is not in C++. Every time you use a cast in C++ it should give you pause for thought.

Your double delete is caused by both copies of the string pointing to the same memory, each thinking they own it.

Please, please, please don't write code like this that uses memset/memcpy on objects. It's just plain wrong.
The difference between malloc and new for C++ objects is that new, aside from allocating memory via malloc, also sets up the vtables for the object and runs the constructors.
Topic archived. No new replies allowed.