Question

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);
Was it helpful?

Solution

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

Please post the constructor body.

OTHER TIPS

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.

Possibly i >= level.SoldierCount?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top