Unheilig
Unheilig

Reputation: 16292

iOS: Error and Crash by NSString with C malloc

Was testing some code and found an error with the following lines:

NSString *stringA = @"C99";
NSString *stringB = (__bridge id)malloc(sizeof (stringA));

It is not necessary to alloc a NSString this way, of course, and I am not required to do that. Again I was just testing on something else and I happened to stumble upon this.

The error reads:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x20)

In the console:

(lldb)

To generalize, perhaps I should ask:

Could we alloc Objective-C objects through the use of malloc?

Has someone encountered this before (which I doubt, because I don't think anyone who uses Objective-C would alloc a NSString this way), but rather than shoving it aside and call it a day, I thought I would ask and see if someone knows what the exact cause of this is and why.

Upvotes: 1

Views: 663

Answers (3)

Greg Parker
Greg Parker

Reputation: 8012

It is possible to use custom allocators for Objective-C objects. The problems with your code include:

  • NSString is a class cluster superclass (similar to an "abstract class") and cannot be instantiated on its own. You would need to use some concrete subclass of NSString. Note that the OS API does not provide any such class.
  • sizeof(stringA) is the size of the pointer variable, 4 or 8 bytes, which is too small to hold an NSString instance. You would need to use class_getInstanceSize() to compute the size.
  • +alloc performs work other than the allocation itself which is not present here. You would need to erase the memory and call objc_constructInstance().
  • ARC forbids the use of the low-level runtime functions that are needed to accomplish the above tasks.

Upvotes: 2

Coldsteel48
Coldsteel48

Reputation: 3512

well as far as I found the closest example of allocating NSSTring Clike is like this:

 NSString* s4 = (NSString*)
 CFStringCreateWithFormat(kCFAllocatorDefault, 0, 
 (CFStringRef) __builtin___CFStringMakeConstantString("%@ %@ (%@)"),  s1, s2, s3);

ofcourse if you want to go lower and lower levels of this allocations , you should watch the CFStringRef class for its lower allocation .

but I hope this answer will satisfy you

found here, also there is more interesting things

http://www.opensource.apple.com/source/clang/clang-318.0.45/src/tools/clang/test/Analysis/NSString.m

Upvotes: 1

user3175170
user3175170

Reputation: 1

I think the question you should be asking is what purpose that code serves.

Note that sizeof doesn't return the number of bytes in stringA, it simply returns the size of the pointer that is stringA. Who knows what lives in that little block of memory that has been allocated to stringB. Maybe it's a string, maybe not. Life is full of mystery.

Upvotes: 0

Related Questions