我正在制作一个可以旋转其行和列的魔方。我的结构是这样的:
typedef struct
{
int **cell;
}face;
在这部分中,我将为单元格分配内存。 (X 是用户输入)
face faceOne; //There are six of this faces
faceOne.cell = (int **)malloc(x * sizeof(int));
for(int i = 0; i < x; i++)
faceOne.cell[i] = (int *)malloc(x * sizeof(int));
然后我填充这些单元格:
for (int i = 0; i < x; i++)
for (int j = 0; j < x; j++)
{
faceOne.cell[i][j] = 0;
printf("%d\n", i);
}
如果 x 大于 3,程序会因段错误而崩溃。我该如何解决这个问题?
最佳答案
faceOne.cell = (int **)malloc(x * sizeof(int));
会是
faceOne.cell = malloc(x * sizeof(int*));
否则,您正在为 x
int 变量分配内存,然后在其上存储 int*
变量。如果 sizeof(int) = sizeof(int*)
那么它不会有任何问题,但在不是这种情况的系统上,您已经为自己赢得了未定义的行为。
要在使用 malloc
时摆脱所有这些 **
最好的方法是这样做
faceOne.cell = malloc(x * sizeof *faceOne.cell);
同样,
faceOne.cell[i] = malloc(x * sizeof *faceOne.cell[i] );
并且也不要强制转换 malloc
的返回值。这抑制了编译器生成的许多警告并且是不必要的。
除此之外,您是否想过如果 malloc
失败并返回 NULL
会发生什么?然后你正在处理一个 NULL
并取消引用它(未定义的行为)。检查 malloc
的返回值,如果它返回 NULL
则处理错误并继续。
关于C - 段错误(核心已转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47738254/