Skip navigation.
 
mlRe: A coding pattern that does not work under Garbage Collection
FROM : Jim Correia
DATE : Fri Nov 09 16:49:22 2007

On Nov 9, 2007, at 10:39 AM, Rick Hoge wrote:

> I've been testing some of our older libraries under GC, and have 
> found one coding pattern (that may well have been bad practice 
> anyway) that really does not work well under GC.
>
> I used to use convenience constructors for NSMutableData objects as 
> a kind of lazy replacement for malloc.
>
> That is, an assignment like this:
>
>  float *myPointer = [[NSMutableData dataWithLength:size*sizeof
> (float)] mutableBytes]; // Memory freed at end of event loop


[...]

> It seems like this (not surprisingly) doesn't work reliably under 
> GC, as the collector obviously has no way of knowing that you are 
> later looking at the memory originally addressed by myPointer.  It 
> keeps track of objects and not pointers.


You kept a (default, no strong or weak modifier) pointer to data 
inside the object, but no one kept a pointer to the object, so it was 
collected.

> As there are probably better ways of approaching this kind of 
> situation, I'd be interested in any suggestions or comments.  The 
> way I was doing it before was probably just bad...


You can allocate GC'd memory with NSAllocateCollectable.

Jim