Why does this program take up so much memory?

Posted by Adrian on Stack Overflow See other posts from Stack Overflow or by Adrian
Published on 2010-06-05T18:10:59Z Indexed on 2010/06/05 18:12 UTC
Read the original article Hit count: 237

Filed under:
|

I am learning Objective-C. I am trying to release all of the memory that I use. So, I wrote a program to test if I am doing it right:

#import <Foundation/Foundation.h>

#define DEFAULT_NAME @"Unknown"

@interface Person : NSObject
{
  NSString *name;
}
@property (copy) NSString * name;
@end

@implementation Person
@synthesize name;
- (void) dealloc {
  [name release];
  [super dealloc];
}
- (id) init {
  if (self = [super init]) {
    name = DEFAULT_NAME;
  }
  return self;
}
@end


int main (int argc, const char * argv[]) {
  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  Person *person = [[Person alloc] init];
  NSString *str;
  int i;

  for (i = 0; i < 1e9; i++) {
    str = [NSString stringWithCString: "Name" encoding: NSUTF8StringEncoding];
    person.name = str;
    [str release];
  }

  [person release];
  [pool drain];
  return 0;
}

I am using a mac with snow leopard. To test how much memory this is using, I open Activity Monitor at the same time that it is running. After a couple of seconds, it is using gigabytes of memory. What can I do to make it not use so much?

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about memory