printf输出scanner.source得到'ELF',文件内容写入指针异常求助
问题:读取文本文件内容却输出'ELF'的排查与解决
尝试将text.txt文件内容写入scanner.source指针,但调用printf打印scanner.source时得到'ELF',无法定位原因。以下是相关代码、文件内容及编译运行命令:
主函数代码
int main(int argc, char *argv[]) { if (argc > 2) { printf("Usage Jlox Script"); return 64; } else if (argc == 2) { runFile(argv[0]); } else { runPrompt(); } }
runFile函数代码
void runFile(char *path) { FILE *file = fopen(path, "r"); if (file == NULL) { printf("file: not found"); exit(65); } fseek(file, 0, SEEK_END); long fileSize = ftell(file); fseek(file, 0, SEEK_SET); scanner.source = malloc(sizeof(char) * (fileSize + 1)); if(scanner.source == NULL){ printf("error occurred allocating memory"); fclose(file); exit(64); } size_t readFile = fread(scanner.source, sizeof(char), fileSize, file); fclose(file); if (readFile != fileSize) { printf("file closing here"); fclose(file); exit(65); } scanner.source[fileSize] = '\0'; printf("scanner source '%s'", scanner.source); run(); if (hadError) exit(65); }
text.txt内容
1 () 2 ** 3 () 4 {};;
编译运行命令
gcc -g modifiedlox.c -o modifiedlox ./modifiedlox.text.txt
问题根源及修复方案
- 命令行执行错误:运行命令
./modifiedlox.text.txt格式错误,正确的执行方式应该是./modifiedlox text.txt,否则程序无法接收到目标文件路径参数。 - 主函数参数传递错误:main函数中,当
argc == 2时,调用runFile(argv[0])是错误的——argv[0]存储的是程序自身的路径(如./modifiedlox),而非用户传入的text.txt路径,应改为runFile(argv[1])。 - 重复关闭文件的隐患:在runFile函数的
readFile != fileSize分支中,已经执行过fclose(file),再次调用fclose(file)会触发未定义行为,需删除重复的fclose(file)。
修正后的关键代码
主函数修正:
else if (argc == 2) { runFile(argv[1]); }
runFile函数修正(删除重复fclose):
if (readFile != fileSize) { printf("file closing here"); exit(65); }
修正后的运行命令:
./modifiedlox text.txt
内容的提问来源于stack exchange,提问作者Ukpa Uchechi
相关产品推荐
相关产品推荐

