How is the size of dynamic memory tracked in C [duplicate] - c

This question already has answers here:
How does free know how much to free?
(11 answers)
Closed 9 years ago.
I understand that using calloc() and malloc() will allocate the specific amount of memory on the heap and return a pointer to the beginning of the allocation.
I also know that free( poinerVar) will de-allocate (free up the allocated memory). However, I cannot visualize how free() knows the amount of memory to de-allocate. Managed languages such as C#, Java keeps track of it's objects for garbage collection, but C surely does not (as far I know).
What is happening at the memory management level that enables the de-allocating of memory using free and passing it just the pointer variable.

The usual approach here is that memory allocation functions are storing metadata about allocated space before actual memory chunk.
In that way, free() just can read memory in front of the actual allocated block and it can find out how much memory should it actually deallocate.

The C standard(s) do not say how that malloc/free works under the covers. Only the external behavior. If you really want to understand it, you need to look at a specific implementation. Check out an open source libc, like the one used by GNU/gcc.

Related

How comes free() doesn't need a length parameter? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C programming : How does free know how much to free?
A random thought occured to me that how comes free(myPtr) doesn't need a length parameter? How does it know how much memory to free?
I can only guess that it keeps track of how much memory it allocates for each particular start address.
This is because malloc saves the information about the length of the allocated chunk, usually in a spot that precedes the address returned to your program. It is not unusual for implementations to allocate an extra storage for a size_t, put the size there, add sizeof(size_t), and return it to you as the malloc-ed pointer. The standard does not call for this implementation, thoug, so alternative implementations are possible, e.g. based on a hash table.
When C allocates memory, it records the length associated with the pointer it gives you. (Often in the area just before the block of memory. But that's an implementation detail.) It keeps some kind of table or list of memory blocks it's handed out, and when you free that memory, C looks up the length of that block based on the value of the pointer.
That's part of why the pointer you pass to free has to be exactly equal to the one you get back from malloc. If it's not, C gets confused and can't find the correct memory block (or its length), and may very well end up "freeing" some memory it was never meant to touch. (If it does that, you may end up with a condition called "heap corruption", which is really bad -- from then on, C might do all kinds of wacky stuff, like trying to allocate some memory in the middle of an existing block and mangling whatever's there.)

how does free know the size of memory to be freed? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C programming : How does free know how much to free?
How does free() know how much memory to be free'd which was earlier allocated by malloc() or calloc()? I mean, both of these functions receive size as parameters, while free only needs the pointer to allocated memory. Then how does free() know that how much to free?
You don't need to know.
It could use any mechanism, it's up to the folks implementing the standard library to decide.
A typical approach is to store block information somewhere just before the pointer returned to the application, but you could also use a totally separate data structure to keep track of allocations, perhaps some kind of tree where the pointer is used as a key to look for information describing that allocation.
If you really want to know, to learn, you can of course read the source code for open sourced C standard library implementations, of which there are at least a couple.
The C standard mandates that the same address returned by malloc be passed to free to deallocate the dynamic memory, So it is clear that malloc maintains some kind of table or mapping for each allocated address (mind you, exact details are unspecefied) where it stores the size of the allocated memory against the address and so it knows exactly how much memory was allocated for every address it returned back to its callers. In a free call it would lookup this mapping to know how much memory to deallocate.
Generally, you have in the free store something like a linked list of allocated resources. The memory manager is going to search that list for the memory block, remove it from the list of allocated resources and insert it back to free resources allowing it to be called again by the allocation functions. How this is done depends on the compiler implementation.

How are malloc and free implemented in C? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do malloc() and free() work?
I read somewhere that calling free twice using the same pointer argument causes undefined behavior. So how does free know how much memory it has to free? Does the heap always allocate contiguous memory when we call malloc/calloc/realloc? Please provide links to relevant articles/posts/blogs etc.
How malloc and free work is implementation defined. Commonly the info about the memory block would be stored in a header just below ptr. But not necessarily.
The great thing about malloc and free is that you don't need to know how they work. The system takes care of the details for you.
I read somewhere that calling free twice using the same pointer argument causes undefined behavior. In order to understand this I must first know how free works?
I'm not sure I agree with this statement. You simply need to follow the rule.
Does the heap always allocate contiguous memory when we call malloc/calloc/realloc?
If you mean that the block of memory returned is contiguous in the address space, then yes that is so. If you mean that successive allocations are sequential, then no.
You can read about an example implementation on the tcmalloc page. It's relatively short and straight forward: http://goog-perftools.sourceforge.net/doc/tcmalloc.html (jump down to Overview)
If you're wondering how malloc requests memory from the OS, it's typically by either calling sbrk or mmap. But that's implementation defined of course.
If you want to see an implementation, look for glibc, which is the GNU implementation of the C standard library, which includes the memory management functionality. But be aware that the exact detail of implementation will be different on other platforms and may change between versions of the standard library.

C Pointers malloc [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C programming : How does free know how much to free?
Hi,
When using malloc(), we specify the size of the allocation, so it knows how much to allocate. However, how does free() knows how many bytes to release? The pointer contains only the starting address of the memory block, not the length of memory block.
Thanks and Regards,
Tazim.
The answer to this is implementation-dependent; the malloc library keeps track of the length somehow, but exactly how it does so is not specified by the C language standard.
A typical approach is to store some header information (including length) before the "starting address" that malloc returns to the caller.
Malloc saves the size of the allocated pointer in some kind of data structure. When you call free it looks up the entry in this data structure and free's that much memory.
When you allocate memory, the run-time library also maintains some internal structures. It has to in order to keep track of what parts of the heap have been allocated. This information also tells it the size of a block of memory given a pointer to that memory.
It depends on the implementation but there's a good chance this information is stored just before the pointer returned.
It's implementation-specific. Some techniques:
There may be more than one pointer. An arbitrarily complex structure could be allocated and you just get a pointer to the user-payload area. The library knows the fixed offset between the pointer given to you and the pointer to the origin of the structure. The other fields could be the size and the links that thread free blocks together.
There may be a separate dictionary. This can have memory-management advantages. One problem with using the allocated block for book-keeping is that the library itself ends up writing to many if not most of the allocated pages. This keeps them dirty (in an MMU sense) and can also prevent them from being shared following a fork. This is a big problem for web servers and has led to specialized implementations of web language systems ("Ruby Enterprise") that differ mainly in memory management core.

How does free() know how much memory to deallocate? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
C programming : How does free know how much to free?
When programming in C, I often usemalloc() to allocate memory and free() to release it:
MyObject* objArr= (MyObject*) malloc(sizeof(MyObject)*numberOfObjects);
/** Do stuff **/
free(objArr);
How does free() know how much memory to deallocate? Does malloc() create a table somewhere to remember pointers and how much memory each pointer pointed to?
If that is the case, will free() fail if I rename the pointer? e.g.:
MyObject* objArr= (MyObject*) malloc(sizeof(MyObject)*numberOfObjects);
MyObject* newPtr= objArr;
free(newPtr); /** Does this fail? **/
What will happen if I increment the pointer and then run free()? e.g.:
MyObject* objArr= (MyObject*) malloc(sizeof(MyObject)*numberOfObjects);
newPtr++;
free(newPtr); /** What happens now? **/
Will it deallocate an additional chunk of memory just off the end of the original array?
The most common way is that it stores some information immediately before the address it returns to you. So if malloc returns the address 0x1004, internally, malloc will have put aside the memory started at 0x0FFC and will store various information such as the size somewhere in the memory between 0xFFC - 0x1003 but the application will be told the allocation starts at 0x1004.
The only thing that matters to free is getting the exact same address as what malloc returned.

Resources