对枚举进行 AND 运算时出现分段错误
我有一个 CField 类和一个包含 CField 二维数组的 CBoard 类。
当我这样做时:
board(0,0)->Is (CField::CHECK)
我在 Is() 方法中遇到段错误。 GDB 在 & 之后指出了我,所以我认为它与它有关。原因是什么?
完整代码:
http://pastebin.com/vetShYsL - 标题
http://pastebin.com/pGNPpa8N - 来源
I have a class CField and a class CBoard containing a 2d array of CField.
When I do this:
board(0,0)->Is (CField::CHECK)
I get a segfault in Is() method. GDB points me right after the &, so I think it's related to it. What's the cause?
Full code:
http://pastebin.com/vetShYsL - header
http://pastebin.com/pGNPpa8N - source
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
板的两阶段构建有点烦人,并且您有一堆您并不真正需要的额外代码来管理它。
错误
这是索引字段 i 而不是 x 的
The 2 phase construction of a board is a bit annoying, and you have a bunch of extra code to manage it that you don't really need.
This is the bug though
index fields by i not x
这可能与
&
无关。最可能的原因是board(0,0)
返回无效(或 NULL)指针。It's probably nothing to do with the
&
. The most likely reason is thatboard(0,0)
is returning an invalid (or NULL) pointer.当您在新创建的
CBoard
对象上调用operator()
时,它会返回一个空指针。取消引用空指针将导致未定义的行为,在您的情况下是段错误。Your
operator()
is returning a null pointer when you call it on a freshly createdCBoard
object. Dereferencing a null pointer will result in undefined behavior, in your case a segfault.您的代码中没有任何内容实际上创建了 CBoard::fields 所需的数组。因此,当调用
CField
代码时,this
是一个无效指针。Nothing in your code actually creates the arrays needed for the
CBoard::fields
. So when yourCField
code is called,this
is an invalid pointer.这里可能会出现许多问题。由于您没有发布
CBoard
的Create
方法,我不知道您是否正确地为字段
分配了存储空间。无论如何,CField* operator() (int x_, int y_) const
可能只是返回 null,因为您编写的条件未计算为 true。您在这里检查空指针吗?另外,为什么不直接使用 std::vector ,而不是参与这种疯狂的双指针内存管理呢?
There could be many possible problems going on here. Since you didn't post the
Create
method ofCBoard
I don't know if you're ever properly allocating storage forfields
. Regardless, it's possible thatCField* operator() (int x_, int y_) const
may simply be returning null because the condition you wrote isn't evaluating to true. Are you checking for a null pointer here?Also, instead of getting involved in this crazy double-pointer memory management, why not just use an
std::vector
?你的棋盘是零对零。如果您查看您的逻辑,在
operator()
中,您将尝试返回fields[0][0]
,但它不存在。Your board is zero by zero. If you look at your logic, in
operator()
, you will try to returnfields[0][0]
, which doesn't exist.