Home > Blockchain >  EXC_BAD_ACCESS when assigning an Objective-C pointer to a member of a C struct
EXC_BAD_ACCESS when assigning an Objective-C pointer to a member of a C struct

Time:08-15

Sometimes but not always I'm getting an EXC_BAD_ACCESS crash assigning an NSMutableDictionary to a struct. I'm obviously doing something wrong but I have no idea what.

typedef struct {
    
    ...
    NSMutableDictionary* headers;
    ...
    
} custom_data_t;

...

- (void)method {

    custom_data_t* customData = malloc(sizeof(custom_data_t));
    customData->headers = [NSMutableDictionary new]; // <- EXC_BAD_ACCESS (code=EXC_I386_GPFLT)

}

CodePudding user response:

First, avoid allocating any C structure which has pointers to Objective-C objects with malloc. It tends to be a problem, because ARC tries to release whatever is set to an ARC-managed pointer when it's not nil upon assigning new values (and since malloc does not zero member variables of the structure object, the pointers may point to some garbage, which ARC will try to release. This is where EXC_BAD_ACCESS error happens). Instead you should use calloc which ensures that all member variables are zero-initialised:

custom_data_t* customData = calloc(1, sizeof(custom_data_t));

Second, while using calloc you should be advised that ARC cannot properly release member variables (because it doesn't know exact length of the pointer), so before freeing a C structure memory, you also need to nullify all its ARC managed pointers:

customData->headers = [NSMutableDictionary new];
// .. some time later ..
customData->headers = nil;
free(customData);
  • Related