xSl*_*ing 0 c malloc segmentation-fault
当我用GCC编译我的代码然后运行它时,当我在代码中调用函数时,它会打印出:“分段错误(内核已转储)”。
我尝试在Google上搜索解决方案。
这是我当前的代码:
char ** saveLevelPositions() {
int x, y;
char ** positions;
positions = malloc(sizeof(char *) * 25);
for (y = 0; y < 25; y++) {
positions[y] = malloc(sizeof(char) * 100);
for (x = 0; x < 100; x++) {
positions[x][y] = mvinch(y, x);
}
}
return positions;
}
Run Code Online (Sandbox Code Playgroud)
我希望该功能能够正常运行,并且只会给出细分错误。
编辑:有关上下文的一些信息,这是GitHub项目的链接:https : //github.com/xslendix/rogue
至于其他的答案和评论所指出的,你应该换你的x和y的使用,所以positions[x][y]应该是positions[y][x]。
另外,您没有使用正确的类型存储的结果mvinch。在curses.h其中说:
typedef unsigned long chtype;
Run Code Online (Sandbox Code Playgroud)
因此,您应该按以下方式分配内存:
chtype ** positions;
positions = malloc(sizeof(chtype *) * 25);
positions[y] = malloc(sizeof(chtype) * 100);
Run Code Online (Sandbox Code Playgroud)
并打开编译器警告,因为编译器应已标记此错误。