为什么我在这段代码中遇到了seg failure(分段错误)

问题描述 投票:0回答:1
int main(int argc, char *argv[]) 
{
    char fileName[50] = {};
    char fileLine[200] = {};
    char *token = NULL;
    char *delimiters = " \n\t";
    FILE *FH = NULL;

    //step 1e to 1g
    strcpy(fileName, argv[1]);
    FH = fopen(fileName, "r+");
    if (FH == NULL)
    {
        printf("File did not open\nExiting...");
        exit(0);
    }

由于某种原因,这段代码总是出现段错误。我使用 valgrind 来识别 strcpy 行的问题,它显示:

Address 0x0 is not stack'd, malloc'd or (recently) free'd

我尝试在 OnlineGDB 中运行它,它一直到第一个打印语句:

File did not open\nExiting...

我尝试增加 fileName 的大小,但即使增加到 1000 也不起作用。我尝试将其减少到 20,但也不起作用。

c segmentation-fault
1个回答
0
投票

您需要检查是否使用至少一个参数调用程序。如果未提供参数,则

argv[1]
为“NULL”,因此会出现段错误。

顺便说一句,如果失败,您还应该致电

exit(1)
(而不是
exit(0)
)。

int main(int argc, char *argv[]) 
{
    char filename[50] = {};
    char fileLine[200] = {};
    char *token = NULL;
    char *delimiters = " \n\t";
    FILE *FH = NULL;

    // ADD THIS
    if (argc < 2)
    {
       printf("You need to provide a file name\n");
       exit(1);
    }
    //

    //step 1e to 1g
    strcpy(filename, argv[1]);
    FH = fopen(filename, "r+");
    if (FH == NULL)
    {
        printf("File did not open\nExiting...");
        exit(1);  // BTW use exit(1) for failure
    }
© www.soinside.com 2019 - 2024. All rights reserved.