Malloc到CGPoint指针访问时抛出EXC_BAD_ACCESS

时间:2010-06-17 17:06:15

标签: iphone c uikit core-foundation

我正在尝试使用Apple编程指南中的一段代码,在尝试将一个指针传递给函数时,我正在获取EXC_BAD_ACCESS,就在执行malloc之后。

(供参考:iPhone Application Programming Guide: Event Handling - Listing 3-6

有问题的代码非常简单:

CFMutableDictionaryRef touchBeginPoints;
UITouch *touch;

....

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

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

现在,当程序进入if语句时,它会将malloc的'输出'分配到point变量/指针。

然后当它尝试将point传递到CFDictionarySetValue函数时,它会崩溃应用程序:Program received signal: “EXC_BAD_ACCESS”.

有人建议不要执行malloc并将point var /指针传递给:&point,但这仍然给了我EXC_BAD_ACCESS

我是什么(看起来像Apple)做错了???

提前致谢。

3 个答案:

答案 0 :(得分:4)

肖恩的回答大多是正确的。根据{{​​3}},它会根据retain的设置方式尝试CFMutableDictionaryRef值。我猜你在创建可变字典时(大概是使用CFDictionaryCreateMutable()),你不会为the documentation for CFDictionarySetValue提供自定义回调。

编辑:

提供自定义回调的另一个选择是为值回调提供NULL

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);

日志:

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

答案 1 :(得分:2)

CGPoint是一个结构,而不是Objective-C / CF对象,所以你需要将它包装在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

答案 2 :(得分:1)

它可能会崩溃,因为当你把它放在字典中时它会试图保留你的CGPoint,除了CGPoint不是真正的对象而是C结构。