Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does dynamic memory allocation work [duplicate]

In C/C++ when you want to dynamically allocate memory usually call malloc void* malloc (size_t size); which returns a pointer to a memory block of size bytes. Once you are done using this memory bloc, you call free() to free the memory back to the heap.

That's all fine, but what happens if you happen to call realloc void* realloc (void* ptr, size_t size); which changes the size of the memory block pointed by ptr. You still call free() when you are done using the memory, but my question is how does the compile know how much memory to free?

Intuitively I can come up with an answer, but I'm interested in implementation details - how is it really done? is it compiler dependent? it is part of a standard?

Thanks in advance!

like image 401
Pandrei Avatar asked Feb 03 '26 18:02

Pandrei


1 Answers

To free memory, you don't generally need to say how much memory you want to free. The allocator already knows how much it gave you, and remembers that. The address of the allocated memory serves as a sort of "key" in the allocator's internal bookkeeping data structures. So all you need to do is give the address of the memory you want to free, and the allocator knows which memory you're talking about.

To be clear: there's no such thing as "partially freeing" some memory. You can't point into the middle of some allocated memory and say "free 100 bytes here". You release precisely what you acquired, no more and no less.

Finally, realloc is just a combination of malloc and memcpy, if you will, perhaps with a small optimization opportunity that allows an existing allocation to "grow" without moving the data. But the idea is the same.

like image 189
Kerrek SB Avatar answered Feb 05 '26 07:02

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!