C ++:损坏的双链表和内存损坏

时间:2014-09-16 19:52:20

标签: c++ memory vector sdl-2

我知道这个问题在stackoverflow中有答案,但我仍然无法解决我的问题,我没有看到错误。我正在使用矢量,我认为我正确使用它,我没有做任何免费或malloc / calloc或其他什么。但是,我确定问题来自矢量,做错了什么。 最奇怪的部分是对程序进行重新编写,它在两个或三个不同的站点中出现。

我使用SDL2和linux上的默认gcc编译代码。我使用Netbeans,使用命令

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

并与-lSDL2 -lSDL2_image链接

错误,其中一个

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

或更不常见:[link] [1]

Valgrind表现出类似的东西,但我不知道如何使用它:[link] [2]

我在这里放了最重要的代码,但是我给你留下了完整的项目,看看你是否想要。希望您能够帮助我。我不确定我是做错了什么,或者问题是以其他方式出现的。

[链接到项目] [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;
}

Shape的一部分(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));
    }
}

命令的一部分秋天,左右相似。这里给出错误

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

    }
}

不重要,但也在这里给出错误。窗口类的部分

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();
}

编辑:删除链接。问题解决了

1 个答案:

答案 0 :(得分:2)

要调试整个事情(这对我们两个人来说完全没有效率)。我对你的源代码进行了简短的观察,并发现了这一点:

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;
}

<=索引的数量超过源和目标向量的大小,这是不好的。更糟糕的是,for循环中的代码是一个明显的内存泄漏。整个功能应该简化为:

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

祝你好运