3

I am trying to write a code to create NSMutableData from malloced buffer.I used freewhendone = YES
1) It gives an error in accessing the buffer after NSData is created.(in memset in below code)
2) The malloced buffer pointer and [data bytes] pointer are different.

Is there any explanation for these?

UWORD8 *rgb_buffer = malloc(u4_stride * u4_height * 3);

NSMutableData *rgbData = [NSMutableData dataWithBytesNoCopy:rgb_buffer

                                                     length:(u4_stride * u4_height * 3)

                                               freeWhenDone:YES];
memset(rgb_buffer, 0, (u4_stride * u4_height * 3));
neeraj
  • 1,191
  • 4
  • 19
  • 47
thar_bun
  • 820
  • 1
  • 5
  • 20
  • You are likely running in ARC and aren't using the rgbData object after the memset; hence, it may be releasing the object early and thus freeing rgb_buffer. See http://blog.bignerdranch.com/296-arc-gotcha-unexpectedly-short-lifetimes/ – iccir Oct 15 '13 at 12:02

1 Answers1

3

From Binary Data Programming Guide

NSMutableData responds to dataWithBytesNoCopy:length:, but the bytes are copied anyway and the buffer is freed immediately.

It gives an error in accessing the buffer after NSData is created.(in memset in below code)

buffer is freed immediately.

The malloced buffer pointer and [data bytes] pointer are different.

NSMutableData create copy of bytes.

Parag Bafna
  • 22,812
  • 8
  • 71
  • 144
  • `If you prefer that the bytes not be copied or freed when the object is released, you can use the dataWithBytesNoCopy:length:freeWhenDone: or initWithBytesNoCopy:length:freeWhenDone: methods passing NO as the freeWhenDone: argument.` This says that using this method bytes are not supposed to be copied. When I try this with freewhendone = NO memset doesn't give segfault but the pointers are still different. – thar_bun Oct 15 '13 at 12:48
  • 1
    NSMutableData responds to these methods, too, but the bytes are copied anyway and the buffer is freed immediately. – Parag Bafna Oct 15 '13 at 13:28