login
Header Space

 
 

dynamic memory allocation

April 22, 2008 - 1:00am
Submitted by kummy_linux on April 22, 2008 - 1:00am.
Linux

To allocate and de-allocate memory we use malloc and free in the programs.My doubt is how free comes to know only the specified size of memory should be freed. what is the logic behind this.........
please need help regarding this..

"man 3 free" will tell you

April 22, 2008 - 3:43am
Anonymous (not verified)

"man 3 free" will tell you how the pointer you give to free must have been returned by malloc and friends. That lets you know that the malloc interface is able to maintain information about memory allocation, which should answer your question.

Re: dynamic memory allocation

April 22, 2008 - 2:03pm
Drew Frezell (not verified)

I believe you are asking how 'free' knows how much memory to return? This is most likely dependent on the implementation of free for whatever library you are using. For glibc 2.7, which is based off of Doug Lea's implementation, the pointer returned from malloc contains a "secret" header which contains the size information. In short, the memory layout looks something like:

+------+  <--- secret memory region malloc stores info
| .... |         used by free and other things
| size |
+------+  <--- mem ptr returned by malloc()
|      |
|      |
|      |
|      |
|      |
|      |
|      |
+------+

Look into malloc/malloc.c for more information, it is far better documented than this brief explanation.

You can find the source for glibc here:

http://ftp.gnu.org/pub/gnu/glibc/glibc-2.7.tar.gz

Drew Frezell

hi, when we use malloc,it

April 25, 2008 - 12:13am
Anonymous (not verified)

hi,
when we use malloc,it returns the first byte of allocated space to the pointer.But while freeing the memory we will mention only the pointer.we are not passing any size related information to the pointer,so how the free() comes to know size of memory to be freed?

thanks a lot, read the file

April 25, 2008 - 1:19am

thanks a lot, read the file malloc/malloc.c in the path u had mentioned.gives the complete information about dynamic memory allocation.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
speck-geostationary