|
-
February 18th, 2008, 06:08 AM
#1
malloc/free question
My question is regarding C, specifically the gcc compiler.
Essentially, I did the following:
Code:
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.
Last edited by c.reilly; February 18th, 2008 at 06:28 AM.
Reason: Added frowny face
Visual C++ 2008 Express Edition
Windows Vista
-
February 18th, 2008, 06:39 AM
#2
Re: malloc/free question
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.
-
February 18th, 2008, 10:07 AM
#3
-
February 18th, 2008, 11:33 AM
#4
Re: malloc/free question
 Originally Posted by c.reilly
My question is regarding C, specifically the gcc compiler.
Essentially, I did the following:
Code:
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..
Code:
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...
Dont forget to rate my post if you find it useful.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|