gnustep-dev
[Top][All Lists]
Advanced

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

Re: mutableCopy in NSArray


From: Nicola Pero
Subject: Re: mutableCopy in NSArray
Date: Tue, 19 Mar 2002 10:53:50 +0000 (GMT)

> > ok, I understand the spirit.  But in this case [NSMutableArray copyWithZone]
> > is wrong :
> > 
> > - (id) copyWithZone: (NSZone*)zone
> > {
> >   /* a deep copy */
> >   unsigned  count = [self count];
> >   id                objects[count];
> >   NSArray   *newArray;
> >   unsigned  i;
> > 
> >   [self getObjects: objects];
> >   for (i = 0; i < count; i++)
> >     objects[i] = [objects[i] copyWithZone: zone];
> >   newArray = [[GSArrayClass allocWithZone: zone]
> >     initWithObjects: objects count: count];
> >   while (i > 0)
> >     RELEASE(objects[--i]);
> >   return newArray;
> > }
> > 
> > unless there is a something else I don't understand.
> 
> Now I'm confused.
> 
> How can one declare
> 
>       id objects[count]
> ??
> 
> count isn't resolvable at compile-time so won't the compiler complain?

gcc automatically allocates space on the stack for it (as if alloca had
been used) ... this is hugely faster than allocating memory using malloc.

but the code is still buggy.

If the array is too big, allocating the space on the stack crashes the
program ... for example 

#include <Foundation/Foundation.h>

int main (void)
{
  CREATE_AUTORELEASE_POOL(pool);
  NSMutableArray *a, *b;
  NSObject *o = [NSObject new];
  int i, count = 10 * 1000 * 1000;

  a = [NSMutableArray new];
  for (i = 0; i < count; i++)
  {
    [a addObject: o];
  }

  b = [a copy];

  RELEASE (pool);
  return 0;
}

this program creates a 10^7 array ... works fine if you don't copy it, but
it segfaults when you copy it.

the solution is that we should check count, and only allocate on the stack
if count is < 10000 (for example); otherwise, allocate using malloc.




reply via email to

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