title: Difference between dataWithBytesNoCopy and dataWithBytes?
body: <p>What is the difference between</p>
  
  <p><code>+ (instancetype)dataWithBytes:(const void *)bytes length:(NSUInteger)length;</code></p>
  
  <p>and </p>
  
  <p><code>+ (instancetype)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length;</code></p>
  
  <p>Also, </p>
  
  <p><code>+ (instancetype)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b;</code></p>
  
  <p>if <code>b == YES</code>, will it free the bytes automatically after converted to data?</p>
  
  <p>I am working on an app and almost finished it. But the last problem is it crashes with memory error when it runs on device. It only crashes when on device, but in simulator it is perfect.</p>
  
  <pre><code>"malloc: * error for object 0x17415d0c0: Invalid pointer dequeued from free list * set a breakpoint in malloc_error_break to debug";
  </code></pre>
  
  <p>I have been working on this issue for several days:
  <a href="https://stackoverflow.com/questions/30320379/ios-my-app-crashes-with-memory-error-if-only-runs-on-device/30321772#30321772">iOS - My app crashes with memory Error if only runs on Device</a></p>
  
  <p><strong>But finally</strong> I found the problem, inside my Encryption and Decryption function, I have this:</p>
  
  <pre><code>Byte *buffer    = (Byte*)malloc(asciiDataLength);
  </code></pre>
  
  <p>After I process with buffer, I convert it to <code>NSData</code>:</p>
  
  <pre><code>NSData *plainData = [NSData dataWithBytesNoCopy:buffer length:asciiDataLength freeWhenDone:YES];
  </code></pre>
  
  <p>This code caused my app to crash continuously, I changed it to </p>
  
  <pre><code>NSData *plainData = [NSData dataWithBytes:buffer length:asciiDataLength];
  free(buffer);
  </code></pre>
  
  <p>Then my app never crash again.</p>
  
  <p><strong>So</strong>, <strong>I have to free the Byte by myself, ARC will not free it for me.</strong></p>