【发布时间】:2016-12-07 04:15:38
【问题描述】:
我正在尝试定义一个全局指针变量,然后可以在主函数中真正设置它,如下所示。但是,在此之后,每当我尝试使用 outputName 时,我都会遇到分段错误。我知道这可能与在开始时将指针设置为等于NULL 有关......任何关于我如何拥有一个然后在 main 中设置的全局指针的帮助都会非常有帮助!这是我的代码中出现错误的部分:
char* outputName = NULL;
int isNumber(char number[]){
int i;
if (number[0] == '-')
i = 1;
while(number[i] != '\0'){
if (!isdigit(number[i]))
return 0;
i++;
}
return 1;
}
void catcher(int signo){
printf("The program is exiting early");
remove(outputName);
exit(1);
}
int main(int argc, char *argv[]){
if (argc != 4){
fprintf(stderr,"Incorrect number of arguments, must supply three.\n");
exit(1);
}
char* inputName = argv[1];
outputName = argv[2];
signal(SIGINT, catcher);
int result = isNumber(argv[3]);
if (result == 0){
fprintf(stderr, "Invalid maximum line length, please enter an integer\n");
exit(1);
}
int maxChars = (atoi(argv[3])) + 1;
if ((maxChars-1) < 1){
fprintf(stderr, "Invalid third maximum line length, please enter an integer greater than zero\
.\n");
exit(1);
}
FILE* inFile = fopen(inputName, "r");
if (inFile == NULL){
fprintf(stderr, "Error while opening %s.\n", inputName);
exit(1);
}
FILE* outFile = fopen(outputName, "w");
if (outFile == NULL){
fprintf(stderr, "Error while opening %s.\n", outputName);
exit(1);
}
char line[maxChars];
int done = 0;
while (!done){
char *readLine = fgets(line, maxChars, inFile);
if (readLine == NULL){
if (errno == 0){
done = 1;
} else {
fprintf(stderr, "Error when reading line from input file");
exit(1);
}
}
int len = strlen(line);
if (line[len-1] != '\n'){
line[len] = '\n';
line[len+1] = '\0';
char current = ' ';
while (current != '\n')
current = getc(inFile);
}
if (!done){
fputs(line, outFile);
if (errno != 0){
fprintf(stderr, "Error when writing line to output file");
exit(1);
}
}
}
return 0;
}
【问题讨论】:
-
所以如果
outputName在上面的代码之后是有效的,那么问题就出在别的地方了…… -
你能提供一个完整的代码块吗?可能是完整的主要功能以及之后您对
outputName所做的事情。 -
这确实取决于您将其设置为什么。如果将其设置为超出范围的局部变量,则会出现未定义的行为。
-
我确实编译了你的代码,它就像一个魅力。您确定这段代码在您的计算机上崩溃了吗?
-
请注意,如果您想合理地确定它们会出现,您应该使用换行符终止
printf()输出;如果您想要更大的确定性,也可以使用fflush(stdout);。然后记下How to avoid usingprintf()in a signal handler。您可能会侥幸逃脱——这不太可能是您遇到麻烦的原因,但由于在分配给outputName后您没有显示任何代码,因此很难知道您在做什么。你说你使用outputName,但唯一显示使用它的地方是在信号处理程序中。你在打断它吗?
标签: c pointers segmentation-fault global errno