gnustep-dev
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Memory leaks galore!


From: David Chisnall
Subject: Re: Memory leaks galore!
Date: Thu, 21 Feb 2013 08:04:47 +0000

On 20 Feb 2013, at 18:00, Jamie Ramone <address@hidden> wrote:

> I'm not sure I follow the deallocation-swap argument. Why would a block of 
> memory that was swapped out be swapped back in when deallocating it? My 
> understanding is that free () simply changes some values in the c runtime to 
> mark that block of memory as available.

Your understanding is, of course, implementation dependent, but in most common 
implementations that I'm aware of it's also wrong.  malloc() implementations 
try very hard to avoid needing any dynamically allocated metadata, so they 
store free-list pointers inside deallocated objects.  When you free a block of 
memory, that block is added to a list.  This is done typically by reading the 
size from the first word before the allocation (so pulling it in) or by 
checking the memory range for allocators that group memory sizes by range, 
finding the correctly-sized free list, and then inserting it into the list.  
The insertion is done by writing a pointer into the just-freed memory.

For Objective-C objects, it's even more explicit, because you deallocate them 
by sending them a -release message which must read the isa pointer, then by 
modifying the retain count (the word before the isa pointer), testing that, 
sending a dealloc message, and then finally calling (via a couple of 
indirection layers) free().

If the object is swapped out, then this means pulling it in from disk, along 
with the rest of the page containing it.  This will likely involve pushing 
something out of memory to disk.  The thing that you are displacing is 
guaranteed to be a more useful thing to keep in main memory than an object that 
is only being pulled in to delete it.  

This also applies for CPU cache usage.  This is a far more scarce resource, and 
you really don't want to be filling up a CPU's cache with data that we don't 
need when killing a process - it will mean that the next process that runs has 
a load of cache misses and incurs a performance penalty.

There are three good reasons for deallocating objects:

- You need to use the memory / address space in your program again.
- The system is low on RAM and so you want to keep your memory footprint to a 
minimum.
- They have side effects in their destructors that must be run.

None of these apply at program termination (the second applies in reverse, as 
this is a good reason to quickly kill the process), with the possible exception 
of the third, which doesn't apply in the case of any of these objects, and is 
considered generally poor style.

David

-- Sent from my Cray X1




reply via email to

[Prev in Thread] Current Thread [Next in Thread]