奇怪的错误:EXC_BAD_ACCESS在我的课堂上

Strange errors: EXC_BAD_ACCESS in my class

本文关键字:ACCESS 我的 课堂 BAD 错误 EXC      更新时间:2023-10-16

这是我的代码:

typedef struct TItemSelector{
  ItemSelectFrame* pItems[2];
} SItemSelector;
class item {
  public:
  void expMethod();
  SItemSelector itemSelector_;
  UILayerButton* startBtn_;
};
void item::expMethod(){
startBtn_ = new UILayerButton();
for (i = 0; i < 3; i++) {
  itemSelector_.pItems[i] = new ItemSelectFrame();
}
startBtn_->callMethodA();
}
void UILayerButton::callMethodA()
{
  this->callMethodB();
}
void UILayerButton::callMethodB()
{
}

this->callMethodB();时,"EXC_BAD_ACCESS"被遮住了。

之后,我找到了一个解决方法:

class item {
  public:
  void expMethod();
  SItemSelector itemSelector_;
  SItemSelector itemSelector2_; // work around
  UILayerButton* startBtn_;
};

然后一切都很顺利...我只是不知道发生了什么,但callMethodB()只是一个空洞的方法,与它无关。

我正在使用Apple LLVM 3.1,默认设置。

更新:修复了我的代码。

在此代码中:

for (i = 0; i < 3; i++) {
  itemSelector_.pItems[i] = new ItemSelectFrame();
}

您正在itemSelector_.pItems末尾写入pItems因为它是一个长度2数组,但您正在编写3元素。

然后,这将覆盖恰好在内存中itemSelector_后立即出现的startBtn_。这解释了您随后阅读现已损坏的startBtn_时的错误。

要么更改环路终止测试,要么增加pItems的长度。我无法判断哪一个是正确的解决方案,但显然您会知道。