Obj C inputs

Discussion in 'Mac Programming' started by Soulstorm, Jun 12, 2006.

  1. Soulstorm macrumors 68000


    Feb 1, 2005
    I am learning more as I go, but I seem to have lost the ball a little in memory management techniques. I want to as you something about this code:

    #include <iostream>
    #include <string>
    #import <Foundation/Foundation.h>
    using std::cin;
    using std::string;
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    	char p[] = "hello message 2";
    	string s;
    	getline(cin, s);
    	NSMutableString *str1 = [[NSMutableString alloc] initWithCString: s.c_str()];
    	NSLog(@"%s and the retain value is %i", [str1 cString], [str1 retainCount]);
    	[str1 setString: [[NSString alloc] initWithCString: p]];
    	NSLog(@"%s and the retain value is %i", [str1 cString], [str1 retainCount]);
    	[pool release];
        return 0;
    Is this code valid in Obj -C++ or I am creating a memory leak here? The point is that I want to create a program that at some part will constantly access an NSMutableString and change its contents to a given string by the user. Although I know I could create an object and initialize it with an InitWithCString every time I call that function and then release it, I am looking for a better way to do it.

    So, to summarize:
    1)Has this code any memory leaks?
    2)Is there any other way to do what I want?
  2. HiRez macrumors 603


    Jan 6, 2004
    Western US
    Yes, I believe you have a memory leak there, and a zombie. Any time you alloc-init an object, you have to send it an explicit release message when you're done with it.

    [str1 release];

    Then, when you assign the second string you perform an alloc-init without ever assigning it to anything. In this case, you aren't assigning it to the str1 variable, you are passing allocated but unassigned memory to it. It's got a retain count of 1 and it will never be released (the retain count will never reach 0 because there is no reference pointing to it).

    In these cases, you could use convenience constructors, which are autoreleased, such as:

    NSMutableString *str1 = [NSMutableString stringWithCString: s.c_str() encoding:NSASCIIStringEncoding];

    (By the way, NSMutableString's initWithCString: method is deprecated, you should not be using it, use the one that specifies an encoding instead.)

    You don't have to explicitly release autoreleased objects, they will be sent a release message when the autorelease pool is released.

Share This Page