Ghimbo21
Ghimbo21

Reputation: 147

Why does free() leaves stuff in memory?

I'm trying to understand how malloc-realloc and free works deeply in C. I've found this page and I was able to understand how a chunk is allocated, but I'm not entirely sure how the free function works, because in my test program it leaves some data in memory after free is called.

This is how the memory look before...

33 0 0 0 0 0 0 0 *q=0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 49 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

...and after the free function:

33 0 0 0 0 0 0 0 *q=112 132 178 223 255 127 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 49 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

I have understood that 33 is the chunk size stored in the chunk header, but I can't understand what the numbers after "q" means when the memory is freed.

Q is the address returned by the malloc.

Thanks!

Upvotes: 0

Views: 114

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222312

The memory management software you are using uses the memory released by free for its own purposes. It needs data to organize the blocks of memory that are available for allocation, and using the memory released by free is a convenient way to do that.

How the memory is used, and whether it is used, is implementation-specific. One implementation may use the freed memory in one way, while another implementation uses it in another way, and a third implementation might not use the freed memory at all, at least for certain sizes of blocks. For example, blocks of a certain fixed size might be tracked by a bitmap maintained elsewhere, possibly using different bitmaps for different fixed sizes.

Upvotes: 2

Related Questions