c - Segmentation fault 导致之前的功能没有发生

标签 c

在一个项目中,我从二维数组中的项目创建一个链表。该数组已正确填充,但我创建链表的方法导致段错误。在尝试调试故障发生的位置时,我在方法调用上方的一行中放置了一条打印语句,但打印语句从未打印出来。但是,如果我注释掉方法调用,打印语句就会打印出来。

main()
{
        struct String *list;
        char words1[100][1000];
        for(int i = 0; i < 100; i++)
                words1[i][0] = '\0';

        char *words2[100];

        for(int i = 0; i < 100; i++)
                words2[i] = words1[i];

        char ** words = words2;

        getStrings(words);

        for(int i = 0; i < 100; i++)
        {
                if(words[i][0] == '\0') break;
                printf("%s\n", words[i]);
        }

        printf("Creating list\n"); //**(RIGHT HERE)** <-----------
        //createList(list, words);
        //sortStrings(list);
        showStrings(list);
        return 0;
}

struct String
{
        char *s;
        struct String *next;
};

void createList(struct String * list, char **words)
{
        list = NULL;
        struct String *node;

        int counter = 0;
        while (1)
        {
                if (words[counter][0] == '\0') break;

                printf("Adding: %s", words[counter]);

                node = (struct String *) malloc(sizeof(struct String));
                node->s = words[counter];
                node->next = NULL;
                list->next = node;
                list = node;
                counter++;
        }
}

void getStrings(char **s)
{
    int count = 0;
    for(int i = 0; i < 1000; i++)
    {
        int ret = scanf("%[^;]", s[i]);
        if(ret < 0) break;
        count++;
        getchar();
    }
}

为什么 createList() 方法中的段错误会导致本应在它之前调用的函数不执行(或至少不显示)?

编辑:在代码中添加了 getStrings() 方法。

最佳答案

printf 函数不会立即将数据写入标准输出,因为这样做可能太慢了。相反,它可能会在 stdout 对象的内部缓冲区中收集数据。一旦缓冲区变满(或有时到达换行符时),其内容就会“刷新”(写入基础文件)。在正常执行期间,此数据也会在程序退出之前写入,但由于您的程序已提前终止,因此无法清空该缓冲区,从而丢失数据。

可以在printf后加上fflush(stdout);语句,强制写入数据。

通常在写入终端缓冲区时会在 \n 处刷新。我怀疑您正在写入管道(可能是您的 IDE 重定向了您的程序输出)。

您可以在此处阅读更多有关文件流的信息:http://en.cppreference.com/w/cpp/io/c

关于 fflush 在这里:http://en.cppreference.com/w/cpp/io/c/fflush

您还可以使用setvbuf 函数来操作文件对象缓冲:http://en.cppreference.com/w/cpp/io/c/setvbuf

关于c - Segmentation fault 导致之前的功能没有发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47082669/

相关文章:

c++ - sizeof 运算符为 C 和 C++ 返回不同的值?

c - 带有 BIO API 的 OpenSSL EVP_aes_128_gcm

c - 值类型转换时地址值不同

您能解释一下 fflush() 和重定向输出发生了什么吗?

c - 如何编写更高效的代码

c - 调用 exec 家族时是否替换、复制或共享环境变量?

c++ - 如何在haskell中封装对象的构造函数和析构函数

c - C 中简单 for 循环中的预期标识符或 '('

c - fgets() 和 sscanf() 只存储数组中的第一个整数

c - getchar 的意外行为