Dorian Hawkmoon
Dorian Hawkmoon

Reputation: 57

C++: corrupted double-linked list and memory corruption

I know this question has answers in stackoverflow, but still i can't resolv my problem, I don't see the error. I'm using vector and I think I'm using it correctly, I'm not doing any free or malloc/calloc or something. However, I'm sure the problem comes with vector, doing something wrong. The most strange part is debbuging the program, it ocurrs in two or three differents sites.

I compile the code with SDL2 and the default gcc on linux. I'm using Netbeans, using the command

g++ -std=c++11 -g -Wall   -c -g -MMD -MP -MF "path/src/game/Game.o.d" -o path/src/game/Game.o src/game/Game.cpp

and linking with -lSDL2 -lSDL2_image

The error, one of this

malloc(): memory corruption (fast): 0x0000000000d86d50 ***
corrupted double-linked list: 0x00000000013fb5d0 ***

or less usual: [link][1]

Valgrind show something like this but I don't know how to use it: [link][2]

I put here the most important code, but I leave you the complete project to see if you want. Hope you can help me. I'm not sure if I'm doing something wrong or the problem come on other way.

[Link to project][3]

Main.cpp

#include ... //some includes
using namespace std;

Shape* shape;
TableBoard board;
Square* square;
Command* command;

void keyDown(SDL_Event &evento) {
    if (evento.type == SDL_KEYDOWN) {
    SDL_Keycode key = evento.key.keysym.sym;
    command = nullptr;
    switch (key) {
        case SDLK_LEFT:
        command = new LeftRight(board, *shape, Direction::LEFT);
        shape->addCommand(command);
        break;

        case SDLK_RIGHT:
        command = new LeftRight(board, *shape, Direction::RIGHT);
        shape->addCommand(command);
        break;

        case SDLK_DOWN:
        command = new FallToGround(board, *shape);
        shape->addCommand(command);
        break;

        case SDLK_ESCAPE:
        exit(0);

    }
    }
}

void newShape() {
    if (shape == nullptr || !shape->isCanFall()) {
    shape = new LShape(*square);
    board.addShape(shape);
    shape->setCanFall(true);

    Command* command = new Fall(board, *shape);
    shape->addCommand(command);
    }
}

int main(int argc, char** argv) {
    Window pantalla;

    SDL_Event evento;
    board = TableBoard(pantalla.getWindow(), 20, 10);
    Board meassureBoard = board.getMeassureBoard();


    SDL_Texture* image = IMG_LoadTexture(pantalla.getPantalla(),
        "resources/images/blue_bold.png");

    //creo una celda, le paso datos de table y que él se pinte
    square = new Square();
    square = new Square();
    square->setGraphics(meassureBoard, image);
    square->setX(3);
    square->setY(1);


    bool letsQuit = false;
    Timer timer{};
    timer.start();
    newShape();
    while (!letsQuit) {
    pantalla.clear();
    shape->executeCommands();
    shape->clearCommandsFinished();

    board.paint(pantalla.getPantalla());
    board.drawLines(pantalla.getPantalla());
    pantalla.actualizar();

    while (SDL_PollEvent(&evento)) {
        if (evento.type == SDL_QUIT) { // Si es de salida
        letsQuit = true;
        } else {
        keyDown(evento);
        }
    }

    newShape();

    if (timer.delta() < 16) {
        SDL_Delay(16 - timer.delta());
    }
    timer.restart();
    }
    return 0;
}

Part of Shape (parent class of LShape)

void Shape::executeCommands() {
    for(vector<Command*>::iterator it = commands.begin(); it != commands.end(); ++it) {
    (*it)->execute();
    }
}

void Shape::clearCommandsFinished() {
    vector<int> remove;
    int index=0;
    for(vector<Command*>::iterator it = commands.begin(); it != commands.end(); ++it) {
    if ((*it)->isAlive() != true) {
        remove.push_back(index);
    }
    index++;
    }

    for(vector<int>::iterator it = remove.begin(); it != remove.end(); ++it) {
        commands.erase(commands.begin()+(*it));
    }
}

Part of command Fall, left and right is similar. Here gives the error

void Fall::execute() {
    if (isAlive() && timer.delta() >= milisecondsFalling) {
    timer.restart();
    bool canMove = true;
    vector<Square> squares = shape->nextMove(0, 1);

    if (shape->isCanFall()) {
        int number=shape->getNUMBER_OF_SQUARES();
        for (int i = 0; i < number && canMove; i++) {
        //check the range
        if (squares[i].getX() < 0
            || squares[i].getX() > board.getNumberColumns() - 1
            || squares[i].getY() < 0
            || squares[i].getY() > board.getNumberRows() - 1) {

            canMove = false;

        } else {
            if (board.isFilled(shape, squares[i])) {
            canMove = false;
            }
        }
        }

        //if we can move, move it definitively
        if (canMove) {
        shape->move(0, 1);
        board.updateBoard();
        }else{
        shape->setCanFall(false);
        }
    } else {
        alive = false;
    } //-> AT THIS EXACTLY MOMENT GIVE THE ERROR!! NOT AFTER, NOT BEFORE

    }
}

Not important, but gives error here too. Parts of the window class

void Window::actualizar() {
    // Mostramos la pantalla
    SDL_RenderPresent(renderer); //EXACTLY POINT WHERE THROW THE ERROR, less frecuent
}

void Window::inicializacion() {
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
    cout << "No se pudo iniciar SDL: " << SDL_GetError() << endl;
    exit(1);
    }

    atexit(SDL_Quit);

    pantalla = SDL_CreateWindow("Tetris",   //CREATED AS PRIVATE IN HEADER INSIDE CLASS: SDL_Window *pantalla;
              SDL_WINDOWPOS_UNDEFINED,
              SDL_WINDOWPOS_UNDEFINED,
              window.w, window.h,
              0);

    renderer = SDL_CreateRenderer(pantalla, -1, SDL_RENDERER_ACCELERATED);

    this->clear();

    if (pantalla == NULL) {
    cout << "Error iniciando el entorno gráfico: " << SDL_GetError() << endl;
    exit(1);
    }

    this->pantalla=pantalla;
}

Window::Window() {
    window.w=1024;
    window.h= 768;

    inicializacion();
}

Edit: links deleted. Problem solved

Upvotes: 2

Views: 7610

Answers (1)

WhozCraig
WhozCraig

Reputation: 66244

I'm not going to debug this entire thing (which would be utterly non productive for either of us). I took a brief look at your source base, and spotted this:

vector<Square> Shape::nextMove(int x, int y) 
{
    //make a copy to not really moving the squares
    vector<Square> clone(numberSquares);
    for (int i = 0; i <= numberSquares; i++) { // <<=== HERE
        clone[i] = *(new Square(squares[i]));
    }
    //get the next move
    moveShape(clone, x, y);
    //return the modified squares
    return clone;
}

That <= is indexing one-past the size of your source and destination vectors, which is BAD. Making matters worse, the code within the for-loop is a blatant memory leak. The entire function should be reduced to this:

vector<Square> Shape::nextMove(int x, int y) 
{
    vector<Square> clone = squares;
    moveShape(clone, x, y);
    return clone;
}

Best of luck

Upvotes: 2

Related Questions