title: Two Objective-C Memory Management Questions: Is Leak Detection Always Right? and Why does autorelease work but not release?
body: <p>I just discovered the following:
  As I expected, releasing my object before I return it causes the app to crash:</p>
  
  <pre><code>   + (NSString *)descriptionOfExpression:(NSArray *)anExpression {
      NSMutableString *expressionDescription;
      expressionDescription = [[NSMutableString alloc] init];  
      for (id object in anExpression) {
      //Do stuff to expressionDescription
      }
  
      [expressionDescription release];
      return expressionDescription;
  }
  </code></pre>
  
  <p>However, I did not expect that the following would cause a memory leak:</p>
  
  <pre><code>    + (NSString *)descriptionOfExpression:(NSArray *)anExpression {
      NSMutableString *expressionDescription;
      expressionDescription = [[NSMutableString alloc] init];  
      for (id object in anExpression) {
      //Do stuff to expressionDescription
      }
  
      return expressionDescription;
      [expressionDescription release];
  }
  </code></pre>
  
  <p>Ultimately, my solution was to do this, instead:</p>
  
  <pre><code>    + (NSString *)descriptionOfExpression:(NSArray *)anExpression {
      NSMutableString *expressionDescription;
      expressionDescription = [[NSMutableString alloc] init];  
      for (id object in anExpression) {
      //Do stuff to expressionDescription
      }
  
      [expressionDescription autorelease];
      return expressionDescription;
  }
  </code></pre>
  
  <p>I understand why autoreleasing it works, but how is a leak being caused by releasing after the value is returned?  </p>
  
  <p>My second question is very related: Are memory leak detection systems always right?  </p>
  
  <p>I realize that the programmers who developed Instruments and the Build and Analyze feature of XCode are far more experienced on this matter than I am, so for now I will assume that they are always right.  However, I have difficulty understanding how a program like Instruments can "know" that memory is being leaked.  I think it should depend entirely on how long I, the programmer, want to use an object.  </p>
  
  <p>This is my understanding of what a "leak" is:</p>
  
  <p>Human definition: Memory is being leaked if I have memory allocated when I am not using it.  </p>
  
  <p>Programming Definition Using Counts: Memory is being leaked when memory is allocated but there are no active objects with a retain count on the object in question.  </p>
  
  <p>Programming Definition Using Accessibility: Memory is being leaked when there is allocated memory that can not be reached from wherever I am in the program right now.  </p>