title: NSData's dataWithBytesNoCopy and writeToFile
body: <p>I have a category method that does somethign like this:</p>
  
  <pre><code>@implementation NSData (additions)
  - (id)someFunc {
  
  char *buffer = malloc(255);
  NSUInteger length = 0;
  while (true) {
      // . . . fill buffer[length++];
  }
  
  realloc(buffer, length);
  return [NSData dataWithBytesNoCopy:buffer length:length freeWhenDone:NO];
  }
  </code></pre>
  
  <p>I am then trying to write the returned data (well call this NSData *fileData):</p>
  
  <pre><code>NSError *error;
  NSData fileData = [NSData someFunc];
  [fileData writeToFile:somePath options:NSDataWritingAtomic error:&amp;error];
  </code></pre>
  
  <p>I get an error:</p>
  
  <blockquote>
    <p>Error Domain=NSCocoaErrorDomain
    Code=512 "The operation couldn’t be
    completed. (Cocoa error 512.)"
    UserInfo=0x20deffd0
    {NSFilePath=/Users/user/Library/Application
    Support/iPhone
    Simulator/4.3/Applications/4C315580-153D-4FA7-9474-E17B58832515/Library/Caches/file.pdf,
    NSUnderlyingError=0x20de1fe0 "The
    operation couldn’t be completed. Bad
    address"}</p>
  </blockquote>
  
  <p>The path exists and is valid. I think the issue is the returned NSData is just a light wrapper around an array allocated with malloc and that writeToFile does not know how to handle this. Does anyone see what I am doing wrong?</p>