iOS stringWithUTF8String (Really CFAllocatorAllocate) EXC_BAD_ACCESS crash, under ARC

1

I have some code that seems as safe as I can make it...but I'm getting EXC_BAD_ACCESS. Not regularly mind, just this one time.

The code:

- (void) deviceListenerCallback:(DeviceEventTypeDef)type data:(void*)data
{
    DeviceInfoDef* o = (DeviceInfoDef*)data;
    char newName[256];
    if (o->DeviceName) {
        strncpy(newName, o->DeviceName, 255);
    } else {
        strncpy(newName, "(null)", 255);
    }
    NSString *deviceNameUTF8 = [NSString stringWithUTF8String:(const char *)newName];

'data' is a pointer passed to us from a C library. The data is present, and uncorrupted.

The characters that end up in newName from the strncpy are "Network Audio\0\0\0\0\0..."

The EXC_BAD_ACCESS is on the last line when I'm calling stringWithUTF8String. the error is:

EXC_BAD_ACCESS (code=1, address=0x30303030)

The call stack is:

CFAllocatorAllocate
................................
5 +[NSString stringWithUTF8String:]
6 -[MyClass deviceListenerCall...

The project is running under ARC.

Can anyone point out the newbie thing I must be doing wrong?

Thanks,

-Ken

ios
nsstring
exc-bad-access
asked on Stack Overflow Mar 14, 2013 by Ken Corey • edited Mar 14, 2013 by nsgulliver

2 Answers

0

It's not clear to me why you are using strncpy() at all given the input string contains the terminating NUL-character.

Why not simply create deviceNameUTF8 (misnamed as that is not UTF-8) directly from o->DeviceName?

- (void) deviceListenerCallback:(DeviceEventTypeDef)type data:(void*)data
{
    DeviceInfoDef* o = (DeviceInfoDef*)data;
    NSString *deviceName;
    if (o != NULL)
        deviceName = [NSString stringWithUTF8String:o->DeviceName];
    else
        deviceName = @"";
answered on Stack Overflow Mar 14, 2013 by trojanfoe • edited Mar 27, 2013 by trojanfoe
0
NSString *deviceNameUTF8 = [NSString stringWithUTF8String: [[NSString alloc] initWithBytes:newName length:255 encoding: NSUTF8StringEncoding]];

I think this should do the trick.

answered on Stack Overflow Mar 14, 2013 by Praveen S

User contributions licensed under CC BY-SA 3.0