views:

69

answers:

6

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

+1  A: 

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.

Mike DeSimone
+2  A: 

It's probably nothing to do with the &. The most likely reason is that board(0,0) is returning an invalid (or NULL) pointer.

Oli Charlesworth
+1  A: 

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?

Charles Salvia
In this case, vector is overkill - I'm always creating and deleting whole table at once.
Xirdus
vector wouldn't be overkill. You spending this amount of time trying to rewrite what vector already does is overkill.
JoshD
+2  A: 

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.

Mark Ransom
A: 

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.

JoshD
My board is 9x9. See edit 2. And my bound checking is correct, because I check for BAD, not GOOD values.
Xirdus
+2  A: 

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];
Greg Domjan
i KNEW it that there is that kind of mistake somewhere! Thanks a lot!
Xirdus
The separate Create() method is useful for me, because I "create" multiple times the same instance of class (to return it to the beginning state).
Xirdus