Question

I am trying to use a snippet of code from a Apple programming guide, and I am getting a EXC_BAD_ACCESS when trying to pass a pointer to a function, right after doing a malloc.

(For Reference: iPhone Application Programming Guide: Event Handling - Listing 3-6)

The code in question is really simple:

CFMutableDictionaryRef touchBeginPoints;
UITouch *touch;

....

CGPoint *point = (CGPoint *)CFDictionaryGetValue(touchBeginPoints, touch);

if (point == NULL)
{
    point = (CGPoint *)malloc(sizeof(CGPoint));
    CFDictionarySetValue(touchBeginPoints, touch, point);
}

Now when the program goes into the if statement it assigns the 'output' of malloc into the point variable/pointer.

Then when it tries to pass point into the CFDictionarySetValue function it crashes the application with: Program received signal: “EXC_BAD_ACCESS”.

Someone suggested not doing the malloc and pass the point var/pointer as: &point, however that still gave me a EXC_BAD_ACCESS.

What I am (and it looks like Apple) doing wrong???

Thanks in advance.

Was it helpful?

Solution

Sean's answer is mostly correct. According to the documentation for CFDictionarySetValue, it's going to try and retain the value according to how your CFMutableDictionaryRef is set up. I'm guessing that when you create the mutable dictionary (presumably using CFDictionaryCreateMutable()), you're not providing custom callbacks for how to handle setting and removing values.

EDIT:

Another option to providing custom callbacks is to provide NULL for the value callbacks:

CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, NULL);

CGPoint * point = (CGPoint *)malloc(sizeof(CGPoint));
point->x = 42;
point->y = 42;

CFDictionarySetValue(dict, @"foo", point);


CGPoint * newPoint = CFDictionaryGetValue(dict, @"foo");
NSLog(@"%f, %f", newPoint->x, newPoint->y);

Logs:

2010-06-17 11:32:47.942 EmptyFoundation[45294:a0f] 42.000000, 42.000000

OTHER TIPS

CGPoint is a struct, not an Objective-C/CF object, so you need to wrap it in an NSValue:

+ (NSValue *)valueWithPoint:(NSPoint)aPoint

http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSValue_Class/Reference/Reference.html#//apple_ref/occ/clm/NSValue/valueWithPoint:

It's probably crashing because it is trying to retain your CGPoint when you put it in the dictionary except CGPoint isn't a real object but instead a C structure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top