Re: NSData dataWithBytes:NoCopy:length free()'s the data (bug)
Re: NSData dataWithBytes:NoCopy:length free()'s the data (bug)
- Subject: Re: NSData dataWithBytes:NoCopy:length free()'s the data (bug)
- From: Jim Correia <email@hidden>
- Date: Thu, 31 Jan 2002 22:41:44 -0500
At 4:25 AM +0100 2/1/02, Allan Odgaard wrote:
On fredag, februar 1, 2002, at 03:44 , Ondra Cada wrote:
You want the newly created data to use directly the
buffer "bytes", which was, though, never allocated. Therefore, naturally,
when it is freed (as the data object gets deallocated) the memory manager
complains.
I don't really see why NSData should call free() on my data.
Because it is documented to do so.
These data can be allocated in a dozen other ways than using the
same malloc() operator which NSData's free() should be paired with,
or they could just be a subset of a malloc allocation..
If Apple really did decide that this would be a good idea, then I
wish they'd state it in their documentation. Cause it sure goes
against my intuition...
It does say that, but not in proximity to the method - earlier in the file.
"If you instantiate a data object with one of the methods whose name
includes NoCopy, however, (such as dataWithBytesNoCopy:length:) the
bytes are not copied and are freed when the data object is released."
Use just dataWithBytes:length:. Or retain the data, never releasing it. Or
malloc the buffer.
When I want to use the NoCopy then it's to cut down on the memory
usage and also improve the time complexity (copy is linear) -- which
is the reason I see for implementing such a feature, not to hand
over the responsibility of calling free(), the latter just make the
code less transparent, because malloc() and free() doesn't get
paired semantically...
If you need more control, use CFData. You get to specify the
contents deallocator, which can be a no-op.
Jim