Memory Allocation Question

Hi Guys,

I am really confused. Basically, what I am trying to do is, I have a struct which has a data member a char *.
Now this char * will allocate a memory. Later on I want to memcpy this object to another object. I have pasted a code below which is similar to what I want to do. Now while writing this code, I was hoping
that it will break, because if you notice, for the second pointer p1 in my code
below, I have only allocated memory to the size of struct, but what about the
memory size that char * inside that struct allocated? Surprisingly
that code is even working.

Can anyone please explain what is going on with this code?

Thanks a lot in advance.

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
27
28
29
30
31
32
33
34
35
#include<iostream>
using namespace std;

struct s {

char *p;
int i;
} ;

int main() {

s* po;
char arr[] = "127.0.0.1";

po = (s *) malloc (sizeof (s));
po->p = (char *) malloc (sizeof(arr)) ;
strcpy(po->p, arr);
po->i = 12;

char *buf;
buf =(char *)  malloc (sizeof(s));
memcpy(buf, po, sizeof(s));

s* p1 = (s *) malloc (sizeof(s));
memcpy(p1, buf, sizeof(s));
cout<<"Result:"<<p1->i<<"         "<<p1->p<<endl;

free(p1);
free(po->p);
free(po);

return 0;

 };
Memcopy just copies each member, so you will have two pointers pointing to the same char array. The array they are pointing to (arr) was not dynamically allocated so does not need to be freed. However what buf points to is dynamically allocated and should be freed.
Topic archived. No new replies allowed.