title: Getting out of memory even with release while reading file in chunks to NSData
body: <p>I'm reading a file on my disk (which can be few GB in size) in 10MB chunks to verify MD5 for it. Method fetchRecords has been simplified as it is a bi</p>
  
  <hr>
  
  <p>t long. The problem is that the data is released when fetchRecords method returns, by then I have few GB in memory. If file is big enough, it causes a crash. <code>[dataChunk release]</code> at the end does not help. Getting a lot of inactive memory until it returns.</p>
  
  <p><img src="https://i.stack.imgur.com/YcH18.png" alt="enter image description here">
  <img src="https://i.stack.imgur.com/8fbG9.png" alt="enter image description here"></p>
  
  <pre><code>- (void)fetchRecords
  {    
      for (DownloadChunkInfo *downloadChunkInfo in [downloadFileInfo chunk])
      {
          NSData *dataChunk = [NSData dataWithContentsOfFile:fileDownloadPath withStartOffset:[downloadChunk startingByte] andEndOffset:[downloadChunk endingByte]];
          if ([dataChunk length] == [downloadChunk length])
          {
              if ([downloadChunk md5] &amp;&amp; [[dataChunk MD5] isEqualToString:[downloadChunk md5]])
              {
                  // Some code
              }
              else
              {
                  // Some code
              }
          }
          [dataChunk release];
      }
  }
  
  + (NSData *)dataWithContentsOfFile:(NSString *)path withStartOffset:(off_t)startOffset andEndOffset:(off_t)endOffset
  {
      FILE *file = fopen([path UTF8String], "rb");
      if(file == NULL)
          return nil;
      uint64_t size = (endOffset - startOffset) + 1;
      void *data = malloc(size);  // check for NULL!
      fseeko(file, startOffset, SEEK_SET);
      size_t realSize = fread(data, 1, size, file);  // check return value, in case read was short!
      fclose(file);
  
      // NSData takes ownership and will call free(data) when it's released
      return [NSData dataWithBytesNoCopy:data length:realSize];
  }
  </code></pre>