不使用参数时的分段错误(核心转储)

时间:2013-10-21 20:06:54

标签: c segmentation-fault

我可能完全以错误的方式做这件事,但考虑到这将是个人使用,让它不那么有效是可以的。

./todo -r运行时,它可以正常工作。

./todo -a运行时,它可以正常工作。

./todo运行时,它会给我segmentation fault (core dumped)

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char *argv[]) {

    if(argc < 1) {
    printf("Not enough variables.");
    }

    if(strcmp("-r",argv[1])==0) {
        printf("\n");

        system("cat .todo");
        printf("\n");
    }
    if(strcmp("-a",argv[1])==0)   {
    char str[BUFSIZ];
    FILE *f;
    f = fopen(".todo","a");
    printf("\n\nTODO list\n\n");
    for(;;) {

        printf("~ ");
        fgets(str,256,stdin);
        if(strcmp(str,"\n")==0) {
            fclose(f);
            printf("\n");
            break;
        }

        fprintf(f,str);
        }
    return 0;
    }
}

3 个答案:

答案 0 :(得分:2)

argv[0]是程序的可执行文件名,计入argc

因此./todoargc=1,但argv[1]为NULL,这会导致strcmp()出现问题。

请参阅argv[argc] ==?

更改您的测试: -

if (argc < 2) 
{
  printf("Not enough variables.");
  return 0; // do this, otherwise we'll plough straight on..
}

答案 1 :(得分:1)

正如其他人所指出的那样,您需要argc < 2而不是argc < 1

此外,您可能希望从if返回,以阻止其余的执行:

if(argc < 2) {
  printf("Not enough variables.");
  return /* some appropriate value here */;
}

答案 2 :(得分:0)

您正在关闭文件句柄,然后仍然尝试写入它:

if (...) {
   fclose(...); <--potentially closing it, depending on the if() results
}
fprintf(...); <--potentially writing to a closed handle.

这是一个不好的想法。