使用 malloc 创建由枚举组成的动态二维数组时的分段库

segmentation vault when using malloc to create a dynamic 2D array, consisting of enums

首先,我不是英语母语者,所以写这样的东西对我来说很难,而且我是新来的。嗨 :)

我在虚拟机和 gcc 上使用 Linux Mint。我正在使用诅咒。几个小时以来,我一直在尝试修复此错误;(

1.) 这是我的枚举:

// Codes on the board
enum BoardCodes {
    BC_FREE_CELL = 1,    // Cell is free
    BC_USED_BY_WORM = 2, // Cell occupied by worm
    BC_FOOD_1 = 3,       // Food type 1; if hit by worm -> bonus of type 1
    BC_FOOD_2 = 4,       // Food type 2; if hit by worm -> bonus of type 2
    BC_FOOD_3 = 5,       // Food type 3; if hit by worm -> bonus of type 3
    BC_BARRIER = 6,       // A barrier; if hit by worm -> game over
};

2.) 这是 cells 变量,在我的结构中 "worm":

enum BoardCodes **cells;

3.) 这就是我想要创建数组的方式:

aboard->cells = malloc((aboard->last_row +2)*sizeof(int*));
if(aboard->cells == NULL) {
    showDialog("Abbruch: Zu wenig Speicher","Bitte eine Taste drücken");
    exit(RES_FAILED); // No memory -> direct exit
}   
int y;
for (y = 0; y < aboard->last_row; y++) {
    // Allocate array of columns for each y
    aboard -> cells[y] = malloc((aboard->last_col + 2)*sizeof(int));
    if((aboard -> cells[y]) == NULL) {
        showDialog("Abbruch: Zu wenig Speicher. Code2","Bitte eine Taste drücken");
    }   
}   

showDialog 里面说 "insufficient memory, press any key"

4.) 我用 gdb 调试了它。分段错误发生在这里:

aboard->cells[y][x]=board_code;

(gdb) print x
 = 40
(gdb) print y
 = 10
(gdb) print aboard->last_col
 = 165
(gdb) print aboard->last_row
 = 28
(gdb) print board_code
 = BC_BARRIER

5.) 我试图打印数组的值:

(gdb) print aboard->cells[1][1]
 = 3087007176
(gdb) print aboard->cells[1][2]
 = 3251580

但它们应该是 BC_FREE_CELL:

void fillwithfreebcs(struct board* aboard)
{
    int y=0;
    int x=0;
    //fill board and screen buffer with empty cels
    for (y = 0; y < aboard->last_row; y ++) 
    {   
        for(x = 0; x < aboard->last_col ; x++ ) { 
              aboard->cells[y][x] = BC_FREE_CELL;
              //placeItem(aboard,y,x,BC_FREE_CELL,SYMBOL_FREE_CELL,COLP_FREE_CELL);
        }   
    }
}

非常感谢:)

(当我使用枚举 Boardcodes* 而不是 int* 时,出现了相同的错误消息。)

rgds,托比。

非常抱歉

由于 return 我忘记删除了,因此从未执行过带有 malloc 的代码...

哈哈