title: Safe way to generically allocate memory in Cocoa which will be automatically deallocated
body: <p>In my Cocoa project I had a bunch of places where I used malloc/free. However several months ago I decided to refactor to leverage ARC and in order to do that I tried to make a replacement for malloc which will return a pointer to something that will be automatically cleaned up. </p>
  
  <p>I used this function (error checking and other logging omitted)</p>
  
  <pre><code>+ (void *) MallocWithAutoCleanup: (size_t) size 
  {
      NSMutableData * mutableData = [[NSMutableData alloc] initWithLength:size];
      void * data = [mutableData mutableBytes];
      return data;
  }  
  </code></pre>
  
  <p>This worked fine for awhile, but recently a random memory overwrite issue came up. I tracked down the cause to this function, what appears to be happening is the NSMutableData instance is being deallocated even though I am keeping a pointer to its mutableBytes. </p>
  
  <p>I guess this is happening because the only <em>direct</em> reference to the object is local and is going away, and the mutableBytes points inside the object so the ARC isn't smart enough to deal with that sort of reference counting.</p>
  
  <p>Is there any way I can refactor this code to retain the mutableData object as long as the mutableBytes pointer is being used (i.e. someone has a reference to it)? I know one option is to just return the NSMutableData itself, but that requires some heavy refactoring and seems very messy.</p>