Re: memory deallocation
Re: memory deallocation
- Subject: Re: memory deallocation
- From: Andrew Farmer <email@hidden>
- Date: Sat, 4 Apr 2009 15:02:24 -0700
On 04 Apr 09, at 14:35, Daniel Luis dos Santos wrote:
Hello,
From what I know so far, memory allocated using the malloc() family
of functions is freed using the free() function. Literal values such
as :
char *aString = "some text";
are automatic values and are deallocated by the compiler
automatically.
This is incorrect. String constants are stored as constant data in
your program and cannot be deallocated (because they were never
allocated in the first place). Passing them to free() will cause an
error like the one you observed.
when you pass as pointer to bytes (like a void*) to cocoa (for
example NSData), what does it do ? It copies the bytes or just
copies the pointer ? If I pass &aString to it that means that at the
end of the scope it will be deallocated, and NSData will have a
dangling pointer ?
Depends on whether you use a NoCopy/freeWhenDone: initializer for
NSData or not. As described in the documentation, NSData will by
default make a copy of the data (the bytes, not the pointer).
In your case, if you're trying to create a NSData object with the
contents of a string, the correct usage is:
char *cstring = "some text";
return [NSData dataWithBytesNoCopy:cstring length:strlen(cstring)];
We use dataWithBytesNoCopy here because the contents of the string are
in constant data, and can be guaranteed to not change or go away.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden