0

I'd like to understand Objective-c's memory management at a lower level. Say I have 100 bytes allocated on the heap to some Objective-c object. What happens to this 100 byte block when the object is dealloc'd?

I'm curious about how the runtime knows that a block of memory is available for re-use after it's dealloc'd. What happens to the actual bytes? Are they set to random values? Or perhaps they keep their values and just get overwritten by other objects later.

SundayMonday
  • 19,147
  • 29
  • 100
  • 154

1 Answers1

2

They keep their value but are marked as unused and overridable.

This behavior is just like the malloc & free functions in C.

AliSoftware
  • 32,623
  • 6
  • 82
  • 77
  • Does the 0th byte in the block mark the 100 byte block as unused? Or perhaps the runtime maintains a table of unused address locations and the size of each location? – SundayMonday Sep 28 '11 at 18:17
  • 2
    Usually, some bits before the memory zone being allocated (like a header for this zone) are used by the low level memory libraries to maintain information about the memory zone itself. Some other runtimes keep a "free-list" (list of free zones) and optimize their reuse to avoid memory fragmentation. But all this really depends on the libraries & runtime used (libc/stdlib) and allocator used – AliSoftware Sep 28 '11 at 18:25
  • 1
    You will probably also find [this other SO question](http://stackoverflow.com/questions/1119134/how-do-malloc-and-free-work) interesting (even if it is C/C++-related) – AliSoftware Sep 28 '11 at 18:28