我正在尝试在 CLI 中编写俄罗斯方块并收到以下错误:
Fatal glibc error: malloc assertion failure in sysmalloc: (old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)
Aborted (core dumped)
我创建了一个日志函数来调查代码中的原因:
std::ofstream log_file("log.txt");
void log(const char* msg) {
log_file << msg << "\n";
log_file.flush();
}
...并在 log.txt 的末尾得到以下内容:
...
----------NEW MAINLOOP----------
has_lost() FALSE
Fall() FALSE
new_random_shape(): Pushing shape
new_random_shape(): Merging shape and board maps
new_random_shape(): Creating a new shape
在此之前有很多,因为程序在出现之前运行了一段时间,但无论如何,这向我表明错误是由我的
new_random_shape()
函数引起的,如下所示:
void new_random_shape(struct program_state* state) {
log("new_random_shape(): Pushing shape");
state->shapes.push_back(state->falling_shape);
log("new_random_shape(): Merging shape and board maps");
for (int i = 0; i < 10; i++) {
*(state->board_map + i) |= *(state->falling_shape->shape_map + i);
}
log("new_random_shape(): Creating a new shape");
state->falling_shape = new Square(((rand() % 10) * 2), 0); // Error is here??
log("new_random_shape(): Checking shape location for edge overlap");
if (state->falling_shape->x + state->falling_shape->width > 20) {
state->falling_shape->x = 20 - state->falling_shape->width;
}
log("new_random_shape(): Done!");
};
这里是
struct program_state
struct program_state {
bool running;
Shape* falling_shape;
int* board_map;
std::vector<Shape*> shapes;
};
这里是
Shape
class Shape {
public:
int x, y, width, height;
int* shape_map;
void (*draw_func)(Shape* s);
void GotoPosition();
bool Fall(int* board_map);
bool Right(int* board_map);
bool Left(int* board_map);
};
...以及
Shape
的方法定义
void Shape::GotoPosition() {
std::cout << GOTO_BOARD_START;
for (int i = 0; i < x; i++) {
std::cout << CURSOR_RIGHT;
}
for (int i = 0; i < y; i++) {
std::cout << CURSOR_DOWN;
}
};
bool Shape::Fall(int* board_map) {
if (y + height == 20) {
return false;
}
y++;
for (int i = 0; i < 10; i++) {
*(shape_map + i) <<= 1;
}
if (overlaps_shape(board_map, shape_map)) {
y--;
for (int i = 0; i < 10; i++) {
*(shape_map + i) >>= 1;
}
return false;
}
return true;
};
bool Shape::Right(int* board_map) {
if (x + width == 20) {
return false;
}
x += 2;
int* new_shape_map = new int[10];
for (int i = 0; i < 9; i++) {
*(new_shape_map + i + 1) = *(shape_map + i);
}
if (overlaps_shape(board_map, new_shape_map)) {
x -= 2;
return false;
}
shape_map = new_shape_map;
draw_func(this);
return true;
};
bool Shape::Left(int* board_map) {
if (x == 0) {
return false;
}
x -= 2;
int* new_shape_map = new int[10];
for (int i = 0; i < 9; i++) {
*(new_shape_map + i) = *(shape_map + i + 1);
}
if (overlaps_shape(board_map, new_shape_map)) {
x += 2;
return false;
}
shape_map = new_shape_map;
draw_func(this);
return true;
};
board_map
是一个指向10个整数数组的指针,每个整数代表游戏盘上的一列,每一位是棋盘上的一个方块,其中整数的最小端是列的顶部,一个1表示一个由不再下降的形状占据的块,0 表示空块。 shape_map
是相同的,但它只包含下降形状的块。
所以,我的问题是,是什么导致了这个错误,以及关于如何修复它的任何想法?任何帮助将不胜感激:)
如果您需要更多信息,请告诉我。