views:

1311

answers:

2

I could not find a post exactly like this, so please forgive me if this is a duplicate.

I am trying to write text using a Core Graphics context. I can do it the first time, no problem, but the second time crashes my iPhone app. Here is a code snippet:

NSString *name = [MyClass getName];
const char *cname = [name UTF8String];
[self drawText:context text:cname];

MyClass and drawText are custom classes/methods but you get the idea... these three lines live in drawRect:

The first time drawRect: is executed, I see the text as expected. However, on any refresh of drawRect:, the line:

const char *cname = [name UTF8String];

causes my app to crash with the cryptic, "GDB: Program loaded." status message.

I get a similar response even when I use the getCString: method. I think I might be missing a fundamental understanding of NSString-to-char-array conversion.

I would appreciate any constructive advice. Thanks in advance.

+3  A: 

The most likely cause is that you're keeping a reference to the previously returned char* and you are dereferencing it on the second call. According to spec, the pointer is not valid to store: The returned C string is automatically freed just as a returned object would be released; you should copy the C string if it needs to store it outside of the autorelease context in which the C string is created.

Remus Rusanu
+3  A: 

It sounds like you're trying to call methods on an object which has been deallocated already. The UTF8String message has the problem that you can't hold onto the returned pointer, since it may become invalidated when the string is released -- you have to copy the string if you need to hold onto it. However, getCString:maxLength:encoding: does not have that problem.

Make sure you're following properly memory management protocol. See the Memory Management Programming Guide for Cocoa, and double-check that you're sending retain, release, and autorelease messages to the proper objects at the proper times. Chances are you're sending an extra release or autorelease when you shouldn't be, or you're forgetting to retain your string somewhere.

Adam Rosenfield