Memory leak

Discussion in 'iOS Programming' started by spilakalb, Sep 26, 2012.

  1. spilakalb, Sep 26, 2012
    Last edited by a moderator: Sep 27, 2012

    spilakalb macrumors member

    Joined:
    Sep 23, 2012
    #1
    Code:
    str = [[NSString alloc]initWithString:@"test leak"];
    str = [[NSString alloc]initWithString:@"second string"];
    In above code there is a leak right? But Instruments Leak not identifying it.

    But
    Code:
    str = [[NSMutableString alloc]initWithString:@"test leak"];
    str = [[NSMutableString alloc]initWithString:@"second string"];
    
    Here leak is identifyiing..Please explain..
     
  2. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #2
    Don't use NSString stringWithString or initWithString.

    Your code becomes:

    Code:
    str = @"test leak";
    str = @"second string";
    
    Do you understand why this will never leak, even though it is against the rules?

    I assume you understand why the second example does leak.
     
  3. spilakalb thread starter macrumors member

    Joined:
    Sep 23, 2012
    #3
    str = @"test leak";
    str = @"second string";
    Here @"test leak" doesn't have any refference .So it cause leak right?
     
  4. spilakalb thread starter macrumors member

    Joined:
    Sep 23, 2012
    #4
    Is it mandatory to set value is nil after release, to avoid the memory leak?
     
  5. jnoxx macrumors 65816

    jnoxx

    Joined:
    Dec 29, 2010
    Location:
    Aartselaar // Antwerp // Belgium
    #5
    if it's a literal string you can't set value to nil, because it's an autoreleased object if i'm not mistaking.
     
  6. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #6
    String literals are constants. They cannot leak. They are real NSString objects but they are special and cannot leak. retain, release, autorelease for string constants have no effect.

    That is why I said in #2 that that code will never leak.

    Also, due to library optimizations stringWithString and initWithString using string literals will return the string literals, not new strings.
     

Share This Page