lundi 3 août 2015

Segmentation Fault on Dungeon Generation code

I'm getting a segfault in this piece of seemingly normal generation code.
I have narrowed it down to this function:

    std::array<uint16_t, 5> makeExit(int rm) {
        std::array<uint16_t, 5> ex;
        std::array<uint16_t, 4> room;
        room = roomList[rm];

        int rx, ry, rx2, ry2;

        while (1) {
            int rw = rand() % 4;
            switch (rw) {
            case 0:
                // north wall
                rx = room[2] + (rand() % room[1]);
                ry = room[3] - 1;
                rx2 = rx;
                ry2 = ry - 1;
                break;
            case 1:
                // east wall
                rx = room[3] + (rand() % room[0]);
                ry = room[2] + room[1];
                rx2 = rx + 1;
                ry2 = ry;
                break;
            case 2:
                // south wall
                rx = room[2] + (rand() % room[1]);
                ry = room[3] + room[0];
                rx2 = rx;
                ry2 = ry + 1;
                break;
            case 3:
                // west wall
                rx = room[3] + (rand() % room[0]);
                ry = room[2] - 1;
                rx2 = rx - 1;
                ry2 = ry;
                break;

            if (mapData[ry2][rx2] == 2) {
                // this is a wall, exit
                ex[0] = (uint16_t) rx;
                ex[1] = (uint16_t) ry;
                ex[2] = (uint16_t) rx2;
                ex[3] = (uint16_t) ry2;
                ex[4] = (uint16_t) rw;
                break;
            }
        }
        return ex;
    }

After hours of debugging, I still have no clue where it is.
The segfault seems to happen after the 3rd or 4th loop.
roomList is an std::vector of std::array<uint16_t, 4> which holds the room data for the dungeon and mapData is a 2D std::vector of uint16_t that holds the tile data. On valgrind, it says
Invalid read of size 2 and Address 0x31 is not stack'd, malloc'd or (recently) free'd
Can you guys help me find the segfault please?

Aucun commentaire:

Enregistrer un commentaire