Submitted by kummy_linux on April 22, 2008 - 1:00am.
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 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.
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.
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?
"man 3 free" will tell you
"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
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:
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
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
thanks a lot, read the file malloc/malloc.c in the path u had mentioned.gives the complete information about dynamic memory allocation.