For the More Curious


The first sentence of the last paragraph says “So, when instantiating a Possession, 20 bytes are allocated from the heap.” Shouldn’t that be “stack”?


All Objective-C objects are instantiated on the heap. The pointer to the Possession is 4 bytes on the stack, the Possession itself is 20 bytes on the heap.



Thanks for the clarification. Maybe I’m just misunderstanding it, but the preceding text in that section makes it sound like it would be on the stack. It says that in addition to the pointer to the object, the stack also holds the pointers to any instance variables for that object. Am I not reading that correctly? The included figure (3.6) even shows a pointer for an instance variable on the stack. If that is the case, then wouldn’t those pointers also take up additional memory on the stack?


Figure 3.6 is showing you a stack frame for fido, which is a method. Remember that a stack frame is the memory allocated for a single execution of a function.

So, the variable str is a local variable in the method fido which points to an object of type NSString.

All instance variables, because they are part of an object, also exist in the heap because they exist inside the memory of an object, which is of course always on the heap.

Basically, it boils down to four different types of variables: local variables, local pointer variables, instance variables, instance pointer variables.

Anything with local in it lives on the stack. Anything with instance lives on the heap, cuz it lives in an instance of some class. Pointer variables point at another place in memory. Typically, a pointer is used to point at an object, so it is pointing at memory in the heap.