Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C: Memory Allocation on stack vs. heap

I am somewhat confused about when things are allocated on the heap (and I need to release them) and when they are allocated on the stack (and I don't need to relese them).

Is there a rule of thumb?

I think in C++ the rule of thumb is that if you use the new keyword they are on the heap. What is the rule with objective c? How can I tell when something is allocated on the stack?

Will this line of code be allocated on the stack?

NSString *user = @"DEFAULT";
like image 559
sixtyfootersdude Avatar asked Sep 11 '25 06:09

sixtyfootersdude


1 Answers

Objective-C is easy in this regard.

All Objective-C Objects Are Always Allocated On The Heap.

Or, at the least, should be treated as if they are on the heap.

For:

NSString *user = @"DEFAULT";

The string object is not technically in the heap, but might as well be. Namely, it is generated by the compiler and is a part of your app's binary. It doesn't need to be retained and released because the class (NSCFConstantString, IIRC) overrides retain/release/autorelease to effectively do nothing.

As for when you do and don't release objects, you should read (and re-read) the Objective-C memory management guide.

(There is one other exception, but it is a rather esoteric detail; blocks start on the stack and you can Block_copy() them to the heap. Blocks also happen to be Objective-C objects, but that is rarely exposed in use.)

like image 150
bbum Avatar answered Sep 12 '25 22:09

bbum