Re: Leaking Memory
Re: Leaking Memory
- Subject: Re: Leaking Memory
- From: Shawn Erickson <email@hidden>
- Date: Mon, 20 Jan 2003 15:42:01 -0800
On Monday, January 20, 2003, at 02:51 PM, Nebagakid wrote:
Hi, I am new to Cocoa development, and I have been hearing about
"Leaking memory". What exactly is memory leaking, and why does it need
to be stopped when coding?
Cocoa actually better said Objective-C doesn't have an automatic
garbage collector like Java has. Instead the programmer has to take
steps to insure that objects allocated (each instance takes up some
amount of memory) are deallocated when no longer needed (as a side note
Java does similar issues with holding references longer then needed or
indefinitely).
This is done in Objective-C using a "retain" counting system that
allows an object to delete itself when it is no longer needed. To ask
an object in Objective-C to remain one simply calls retain(). This will
increment the retain count. To inform an object that you do not need it
you call release() to decrement the retain count, the opposite of
retain. If the retain count reaches zero the object will assume it is
not needed an delete itself (free the memory related to the object).
Anyway if retain count isn't correctly managed you can end up with the
retain count never reaching zero and hence never being freed. This is
generally referred to as leaking an object or "leaking memory". If this
is repeated you will begin to consume application memory and if you
leak enough the process could die because it has exhausted all of its
virtual memory space. Generally the application would die at this point
in time (on Mac OS 9 this could cause the OS to die).
You could also have an issue with releasing an object (or not retaining
it) when you still need it to exist. This results in something you need
being freed.
To manage issues like this the Cocoa frameworks follow a simple memory
management pattern that can be stated as the following: If you created,
copied or retained an object then it is your responsibility to release
it.
See the following for a better run down of things...
http://www.stepwise.com/Articles/Technical/2001-03-11.01.html
http://cocoadev.com/index.pl?MemoryManagement
http://developer.apple.com/techpubs/macosx/Cocoa/TasksAndConcepts/
ProgrammingTopics/MemoryMgmt/index.html
Objective-C, C, C++ as well as most other programming languages leave
memory management up to the programmer.
-Shawn
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.