• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: memory deallocation
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


  • Follow-Ups:
    • Re: memory deallocation
      • From: Michael Ash <email@hidden>
References: 
 >memory deallocation (From: Daniel Luis dos Santos <email@hidden>)

  • Prev by Date: memory deallocation
  • Next by Date: Re: memory deallocation
  • Previous by thread: memory deallocation
  • Next by thread: Re: memory deallocation
  • Index(es):
    • Date
    • Thread