Reputation: 3087
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
Upvotes: 0
Views: 449
Reputation: 14115
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
for (int i = 0; i < x; ++i)
fields [x] = new CField [y];
index fields by i not x
for (int i = 0; i < x; ++i)
fields [i] = new CField [y];
Upvotes: 2
Reputation: 53319
There could be many possible problems going on here. Since you didn't post the Create
method of CBoard
I don't know if you're ever properly allocating storage for fields
. Regardless, it's possible that CField* 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
?
Upvotes: 1
Reputation: 12814
Your board is zero by zero. If you look at your logic, in operator()
, you will try to return fields[0][0]
, which doesn't exist.
Upvotes: 0
Reputation: 308402
Your operator()
is returning a null pointer when you call it on a freshly created CBoard
object. Dereferencing a null pointer will result in undefined behavior, in your case a segfault.
Upvotes: 2
Reputation: 272657
It's probably nothing to do with the &
. The most likely reason is that board(0,0)
is returning an invalid (or NULL) pointer.
Upvotes: 2
Reputation: 42825
Nothing in your code actually creates the arrays needed for the CBoard::fields
. So when your CField
code is called, this
is an invalid pointer.
Upvotes: 1