Search code examples
objective-cmemory-managementheap-memorystack-memorystack-frame

Stack - Frame - Heap in Objective-C


All questions I found on this site refer only to Stack vs Heap and don't discuss Frame so here is my question. Don't get the difference between all three.

What I know:

Frame: A frame is like a blackboard for instance variables of a function. While the function is running all instance variables are stored inside the frame of that function. When a function is called its frame is created on top of the stack.

Stack: A stack can be visualized as a physical stack of frames. When a method (or function) is executed, it allocates a chunk of memory from the stack.

Heap: All object pointers live on the heap.

Stack and Frame is clear (I think) but am I right with my Heap statement?


Solution

  • Heap: All object pointers live on the heap.

    Stack and Frame is clear (I think) but am I right with my Heap statement?

    Not quite. Most(*) dynamically allocated objects live on the heap, the pointers to those objects live in other objects (or variables, they are essentially the same thing) - which may be on the stack or heap. This distinction between "objects" and "pointers to objects" is important in Objective-C (it is not so in all languages), and its not correct to say all "object pointers live on the heap".

    (*) "Most" as it is possible, and sometimes quite useful, to allocate dynamic objects on the stack. You cannot do this with Objective-C objects, but you can do this with C objects (and C is part of Objective-C). Don't concern yourself yet with this, this footnote serves more to illustrate that the model being described here is a simplification.