Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 How does free work in C?
Index -> Programming, C -> C Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Andy




PostPosted: Sun Oct 14, 2007 11:20 pm   Post subject: How does free work in C?

How does free know how many bytes to allocate? Does malloc keep map the size of the allocated memory onto the pointer? What would happen if I call

c:

void * p = malloc(16);
free(p+8);
free(p+4);
free(p);
Sponsor
Sponsor
Sponsor
sponsor
md




PostPosted: Mon Oct 15, 2007 12:12 am   Post subject: RE:How does free work in C?

malloc() is system/compiler dependent so it's hard to give a specific answer. Basically however it does keep track of what memory it's allocated and depending on how it does so your calls to free could fail or succeed.

If malloc() were implemented as a bitmap or memory blocks then you'd probably be fine with all the calls; free() would most likely return true, however the results would still be undefined and it would be very poor form. If malloc() stores information in a linked list type structure then free() would probably fail for the first two and succeed for the third.

Weather it works or not, that's horrible form however. Say you do this:
C:
void * p = malloc(16), *q;
free(p+8);
q = malloc(8);
*p = <some 16bit string>

Depending on how malloc() and free() work you might end up overwriting q when you write to p, or you might not. It's impossible to say unless you know exactly the compiler being used.
Junkhead




PostPosted: Thu Oct 18, 2007 8:16 pm   Post subject: Re: How does free work in C?

Says right in the documentation.
free() only works on pointers that have been allocated with malloc(), calloc(), or realloc().
Pretty sure it's a standard.
Display posts from previous:   
   Index -> Programming, C -> C Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: