【发布时间】:2016-06-01 13:58:02
【问题描述】:
我有一个名为 example 的 elf 文件。我编写了以下代码,它以二进制模式读取示例文件的内容,然后我想将它们的内容保存在另一个名为 example.binary 的文件中。但是当我运行以下程序时,它显示了一个分段错误。这个程序有什么问题?我找不到我的错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// typedef macro
typedef char* __string;
//Function prototypes
void readFileToMachine(__string arg_path);
int main(int argc, char *argv[]) {
__string pathBinaryFile;
if(argc != 2){
printf("Usage : ./program file.\n");
exit(1);
}
pathBinaryFile = argv[1];
readFileToMachine(pathBinaryFile);
return EXIT_SUCCESS;
}
void readFileToMachine(__string arg_path){
int ch;
__string pathInputFile = arg_path;
__string pathOutputFile = strcat(pathInputFile, ".binary");
FILE *inputFile = fopen(pathInputFile, "rb");
FILE *outputFile = fopen(pathOutputFile, "wb");
ch = getc(inputFile);
while (ch != EOF){
fprintf(outputFile, "%x" , ch);
ch = getc(inputFile);
}
fclose(inputFile);
fclose(outputFile);
}
【问题讨论】:
-
strcat(pathInputFile, ".binary");覆盖尚未由您的程序分配的内存。 -
@user3646905 阅读一本好的 C 教科书或遵循教程。了解指针。
-
为参数、扩展和终结符分配足够的内存,并检查
fopen的结果。 -
而你的 typedef
typedef char* __string是个坏主意。它让人相信存在“字符串”类型,但实际上__string只是指向 char 的指针。 -
不要以两个下划线开头自己的标识符!以两个下划线开头的标识符(如
__string)保留供标准库内部使用。
标签: c linux segmentation-fault ubuntu-14.04