views:

458

answers:

4

I create a pointer-to-pointer of a class object and when I try to create a new object using the pointers it seg-faults. Why does this happen?

struct Level
{   
        int SoldierCount;
        Soldier **soldier;
        int taskCount;
        int *taskPercentage;
        int *taskBitmapX;
        int *taskBitmapY;
}level;

void createMap()
{
    //Input and Declartion of various variabls goes here

    level.soldier = new Soldier* [level.SoldierCount];

    //Seg Faults Here
     level.Soldier[i] = new Soldier(initX, initY, initDirection, steps);  

}

The Soldier Class Constructor:

Soldier(int, int, int, int);
+2  A: 

I can not find any segfault related problems in your code.

But I'm confused as to why your case sensitivity does not match:
The class is called "Soldier" and the Soldier** is called "soldier".

But you write:

level.soldier = new soldier* [level.SoldierCount];

and:

level.Soldier[i] = new Soldier(initX, initY, initDirection, steps);

If the code really compiles as you've written it, this could be the problem.

arturh
My bad. Corrected the code now.
Shrivara
Always copy/paste source code when showing it to others. If we can't be sure that the code you posted is the code you have, how can we possibly answer the question? Copy/paste, so you don't introduce typos or other errors that aren't there in the actual code you're working with.
jalf
I was playing around with markdown and messed it up. Sorry.
Shrivara
+2  A: 

With empty Soldier constructor your code works fine (except for corrected typos, like lowercase level.soldier[])

Please post the constructor body.

Quassnoi
The constructor was the problem, I was over-looking it all the while. Thanks.
Shrivara
A: 

What is the value of level.SoldierCount? What is the value of i

The only way a segfault can occur is if you access unallocated memory. In the line you highlighted, the only place that can happen is in the array (or inside the constructor, which you didn't post the code for). Most likely, you're accessing the array out of bounds.

jalf
+1  A: 

Possibly i >= level.SoldierCount?

Sunlight