为什么这段代码在使用Apple LLVM编译时崩溃,但在LLVM / GCC中却没有崩溃



我正在尝试获取以下代码:http://code.google.com/p/switchcontrol/source/browse/trunk/code/AFSwitchControl.m Xcode 4.5.2中的Apple LLVM下编译。当使用 LLVM/GCC 编译时,它可以工作,但在第 198 行切换到 Apple LLVM 时,mouseDown 方法崩溃:

NSRect knobRect = _AFSwitchControlKnobRectForInsetBackground(slotRect, _offset);

因为_offset没有设置。它应该在绑定方法中设置,并带有以下行:

[self setOffset:(CGFloat)[self state]];

但出于某种原因,似乎没有在LLVM下设置任何内容。我的绑定调用如下所示:

[control bind:NSValueBinding toObject:self withKeyPath:@"isToggleSwitchOn" options:nil];

知道为什么控件的状态在 LLVM 下不返回任何内容吗?谢谢!

问题实际上出在上面的几行,在调用_AFSwitchControlPartRects中。

- (void)mouseDown:(NSEvent *)event {
    NSRect textRect, backgroundRect;
    _AFSwitchControlPartRects([self bounds], &textRect, &backgroundRect);
    NSRect slotRect = _AFSwitchControlInsetBackgroundRect(backgroundRect);
    NSRect knobRect = _AFSwitchControlKnobRectForInsetBackground(slotRect, _offset);

要_AFSwitchControlPartRects的第二个参数 &textRect 是指向 rect 的指针。

但是,在函数的实现中,该参数应该是指向两个矩形足够空间的指针。

NS_INLINE void _AFSwitchControlPartRects(NSRect bounds, NSRect *textRects, NSRect *backgroundRect) {
    NSDivideRect(bounds, textRects, backgroundRect, NSWidth(bounds)/5.0, NSMinXEdge);
    textRects[1] = _AFSwitchControlInsetTextRect(NSOffsetRect(textRects[0], NSWidth(*backgroundRect), 0));
    textRects[0] = _AFSwitchControlInsetTextRect(textRects[0]);

当它写入 textRects[1] 时,它会在 -mouseDown 的堆栈上涂鸦。缓冲区溢出。

在我看来,它就像发生在自我身上一样,所以自我的下一个被贬低将会死亡。这恰好是使用_offset。

最新更新