Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Objective-C 2.0 garbage collection collect C structures?

What exactly does the Objective-C garbage collector collect? For example, if I'm writing a program in Objective-C 2.0, and I use some plain C structs, does my code need to worry about manually freeing that memory?

like image 817
Ross Andrews Avatar asked Apr 19 '10 18:04

Ross Andrews


People also ask

Is Objective C garbage collected?

Objective-C 2.0 adds garbage collection to the language as a replacement to the traditional retain / release reference counting scheme. Garbage collection is automatic object memory management.

What is garbage collection in data structure using C?

Garbage collection (GC) is a memory recovery feature built into programming languages such as C# and Java. A GC-enabled programming language includes one or more garbage collectors (GC engines) that automatically free up memory space that has been allocated to objects no longer needed by the program.

Which data structure is used by garbage collector?

Garbage collection (GC) is a dynamic technique for memory management and heap allocation that examines and identifies dead memory blocks before reallocating storage for reuse. Garbage collection's primary goal is to reduce memory leaks.

Does C language do garbage collection?

Garbage collection is a tool that saves time for programmers. For example it replaces the need for functions such as malloc() and free() which are found in C. It can also help in preventing memory leaks. The downside of garbage collection is that it has a negative impact on performance.


2 Answers

For heap memory, you're on your own by default. Unless you allocate heap memory with NSAllocateCollectable or NSReallocateCollectable, or explicitly hand a CoreFoundation object over to the garbage collector via an API like NSMakeCollectable, the GC has no idea about your memory, and won't manage it for you. Conversely, when GC is enabled, Objective-C objects created with +alloc/-init are managed by GC unless you explicitly tell it otherwise with a complementary API call.

http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/GarbageCollection/

like image 57
Quinn Taylor Avatar answered Oct 08 '22 19:10

Quinn Taylor


If you use malloc() to allocate a structure on the heap, then I really doubt it (the man page doesn't mention anything about it, but it's possible that Apple rewrote malloc for the ObjC2 runtime). If you use NSAllocateCollectable(), then yes.

If the structure was created on the stack, then there's no need for collection, since it will be destroyed as soon as the frame exits.

like image 24
Dave DeLong Avatar answered Oct 08 '22 18:10

Dave DeLong