In C, how does malloc determine when to reclaim freed space for new allocations?

Viewed 146

I'm reading an example snippet of C code from Hacking: The Art of Exploitation, which does the following:

  1. Allocates 50 bytes on the heap for variable A using malloc()
  2. Allocates 10 bytes on the heap for variable B using malloc()
  3. Frees the 50 bytes allocated for variable A using free()
  4. Allocates 15 bytes for variable C using malloc()

In this example, when I pay attention to the memory addresses for each of these, I can see that they continue to increase in value for each subsequent allocation, that is for A, B, AND C.

The example I'm reading is from 2008, and they include an example like so:

  1. Allocates 100 bytes on the heap for variable A using malloc()
  2. Allocates 10 bytes on the heap for variable B using malloc()
  3. Frees the 50 bytes allocated for variable A using free()
  4. Allocates 15 bytes for variable C using malloc()

They allocate 100 bytes with malloc to demonstrate a situation where the allocation algorithm within malloc chooses to reclaim freed space for new allocations. I can notice this happening by looking at the memory addresses: The address of variable B is still higher than the address of variable A, however when C is allocated, it takes the freed space where variable A was allocated (and then freed).

However, on my machine, I experimented with this and noticed that I had to allocate 1033 bytes for variable A to see the situation where my malloc chose to reclaim freed space for new allocations (so when memory for variable C is allocated, it takes on the available address that A had before it was freed).

My question is:

What are the factors that determine where this limit exists?

My guesses include:

  • Differences between x86 64 bit architecture and x86 32 bit architecture
  • New versions of gcc and c
  • Operating system differences

I'd appreciate any thoughts, explanations or history that you may find interesting

0 Answers
Related