代码之家  ›  专栏  ›  技术社区  ›  kdbdallas

Malloc到一个CGPoint指针,在访问时抛出EXC\u BAD\u访问

  •  3
  • kdbdallas  · 技术社区  · 15 年前

    (供参考: 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

    当它试图通过 进入 CFDictionarySetValue 使应用程序崩溃的函数: Program received signal: “EXC_BAD_ACCESS”.

    马洛克 并通过 变量/指针为: &point 然而,这仍然给了我一个机会 EXC_BAD_ACCESS .

    3 回复  |  直到 15 年前
        1
  •  4
  •   Dave DeLong    15 年前

    肖恩的回答基本上是正确的。根据 the documentation for CFDictionarySetValue retain 价值取决于你的 CFMutableDictionaryRef 已设置。我猜当您创建可变字典(大概是使用 CFDictionaryCreateMutable() how to handle setting and removing values .

    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
    
        2
  •  2
  •   Dave Dribin    15 年前

    CGPoint是一个struct,而不是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 :

        3
  •  1
  •   Sean    15 年前