SIGSEGV Segmentation fault. Yet another one.

I have a really weird seg fault. This is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Map::Map(TileSet &t, string fileName)
{
    int amountOfLayers;
    ifstream file;
    file.open(fileName.c_str());
    file>>amountOfLayers;
    cout<<amountOfLayers<<"\n";
    for(int i = 0; i < amountOfLayers; i++)
    {
        Layer layer(t, file);
        layers.push_back(layer); //SIGSEGV FAULT
    }


}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Layer::Layer(TileSet& t, ifstream& file)
{
    for(int i = 0; i < FIELDHEIGHT; i++)
    {
        vector<Tile*> temp;
        grid.push_back(temp);

        cout<<"\n";


        for(int j = 0; j < FIELDWIDTH; j++)
        {
            int id;
            file>>id;
            sf::Sprite sprite;
            Tile* tile;
            t.getTile(tile, id);
            tile->sprite.SetPosition(j*32, i*32);
            grid[i].push_back(tile);
            cout<<id;
        }
    }
}


It calls the constructor only once, Layer constructor completes, and then all out of a sudden I get a SIGSEGV fault :S
Last edited on
1
2
3
            Tile* tile;
            t.getTile(tile, id);
            tile->sprite.SetPosition(j*32, i*32);
tile is not initialised.
¿what does getTile do?
getTile is this:

1
2
3
4
5
void TileSet::getTile(Tile* tile, int id)
{
    Tile* tile_(tiles[id]);
    tile = tile_;
}


Where tiles is a map of pointers to tiles.
The SIGSEGV fault occurs when I try to push layer back in the layers vector.
I marked it in the initial post.
But the pointer is passed by copy there.
Pass it by reference or return the value.
That changes the value of the local variable "title", but it won't affect the value passed to the function. If you really need to change the address in the pointer, pass it as a reference:
void TileSet::getTile(Tile*& tile, int id);

But why not just return the address of the pointer?
Thanks for the help both of you! It works now :)
But why did that throw a SIGSEGV error when I try to push it back, and not immediately?
I would have thought this was the offending line:
tile->sprite.SetPosition(j*32, i*32);
(as tile doesn't point to anything).

My debugger puts the breakpoint on the line after the exception, so perhaps the same has happened here, and in fact this line is responsible.
Topic archived. No new replies allowed.