Click to See Complete Forum and Search --> : malloc/free question


c.reilly
February 18th, 2008, 05:08 AM
My question is regarding C, specifically the gcc compiler.
Essentially, I did the following:


void *ptr = malloc( (sizeof(int)*2) + (sizeof(char)*STRLEN) );
void *p = ptr;
*(int*)p = 1;
p += sizeof(int);
*(int*)p = 2;
p += sizeof(int);
strcpy((char*)p, "hello");

// did some stuff

free( ptr );


Did I free the memory properly?
I know the first integer is freed, but I accidentily printed the values of all these locations and the second integer's and string's values were still intact.

S_M_A
February 18th, 2008, 05:39 AM
The memory is properly freed. The fact that the memory still contains your old data only means that it's not yet allocated and used by another thread.

Marc G
February 18th, 2008, 09:07 AM
[ moved thread ]

code_carnage
February 18th, 2008, 10:33 AM
My question is regarding C, specifically the gcc compiler.
Essentially, I did the following:


void *ptr = malloc( (sizeof(int)*2) + (sizeof(char)*STRLEN) );
void *p = ptr;
*(int*)p = 1;
p += sizeof(int);
*(int*)p = 2;
p += sizeof(int);
strcpy((char*)p, "hello");

// did some stuff

free( ptr );


Did I free the memory properly?
I know the first integer is freed, but I accidentily printed the values of all these locations and the second integer's and string's values were still intact.


Is it compiling..???
According to me there should be many compilation errors..

void *ptr = malloc( (sizeof(int)*2) + (sizeof(char)*STRLEN) ); //allright
void *p = ptr; //allright
*(int*)p = 1; //allright
p += sizeof(int); //should be a compilation error..mind you that p is still of type void* and on void* you can not have arithmatic operation because size of the data it should be holding is not known..
*(int*)p = 2; //I think its all right here...
p += sizeof(int); //Again a compilation error.
strcpy((char*)p, "hello"); //allright...

// did some stuff

free( ptr ); //allright memory is freed..
immediatley assign ptr to NULL and p to NULL; otherwise you have two dengerouse dangling pointer...