【发布时间】:2022-01-14 21:16:50
【问题描述】:
我正在用 C 语言编写一个命令行工具来控制 UNDERTALE 保存文件(因为为什么不这样做),每当我从用户那里获取输入时,我都会遇到分段错误。
这是我所有的代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#define KILOBYTE 1024
/* The 'm()' is so i know what line the fault happens on */
void m(void) {
printf("X");
}
int main(int argc, char**argv) {
FILE *file;
if (file = fopen("~/.undersave", "r")) {
// Do some code that I haven't written yet
}
else {
char path[KILOBYTE] = "";
printf("It seems that this is your fist time using UNDERSAVE.\nWe just need to go through some quick installation steps.\nWhere do you want your UNDERTALE save folder to be located? >>> ");
m();
fgets(path, KILOBYTE, stdin);
/*
The fault happens here, when it asks me,
i put in the input like normal, but
when I press enter, I get a fault before
it prints 'X'
*/
m();
mkdir(path, 0777);
m();
file = fopen("~/.undersave", "w");
m();
fprintf(file, "%s", path);
m();
fclose(file);
}
return 0;
}
【问题讨论】:
-
Re "'m()' 让我知道故障发生在哪条线路上",oof。学习使用调试器。
gdb可以很容易地给你一个堆栈跟踪(命令是btIIRC)。而且,如果您使用gcc或clang,您应该会发现-fsanitize=address非常有用。 -
printf使用缓冲输出,因此除非刷新输出缓冲区,否则您将看不到任何内容。通常,您只需在 printf 末尾使用换行符 ('\n') 即可。我推荐void m(int location) { printf("X%d\n", location); },然后将调用更改为m(1)、m(2)等。
标签: c macos input segmentation-fault fgets