【问题标题】:Getting Segmentation fault (core dumped)出现分段错误(核心转储)
【发布时间】:2014-12-17 17:51:43
【问题描述】:

所以我试图读取行,然后用 strtok 将它们分成两部分。因此,如果我要阅读“nice dog”,它将首先打印我阅读的内容,然后在下一行使用 strtok 命令“nice”和“dog”进行打印。但是在第二次输入之后我得到了分段错误。另外,free(buf) 是做什么的?我已经看到错误出现在这一行:“strcpy(name, strtok(NULL, ""));"这是代码:

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

int main()
{
    char *buf;
    char command[32];
    char name[32];

    while((buf = readline("\n"))!=NULL)
    {
        if (strcmp(buf,"exit")==0)
            break;

        printf("%s\n",buf);

        strcpy(command, strtok(buf, " "));
        printf("%s\n", command);
        strcpy(name, strtok(NULL, " "));
        printf("%s\n", name);
        if(buf[0]!=NULL)
        add_history(buf);
    }
    free(buf);
    return 0;
}

【问题讨论】:

  • readline 是做什么的?
  • 在使用之前检查您的strtok 输出。
  • 读取您的线路输入
  • Free 释放从堆中获得的内存,因此使用 malloc 或相关函数之一。每当你 malloc 某些东西时,你必须释放它,否则你会出现内存泄漏
  • readline 可能有问题。给我们看readline的代码就更清楚了。

标签: c


【解决方案1】:

如果是NULL,则必须检查strtok 的结果,这意味着找不到任何令牌,您将获得segmentation fault

char *pointer;
pointer = strtok(buf, " ");
if (pointer != NULL)
    strcpy(command, pointer);

另外,readline 会在每次调用时分配新内存,因此您应该在 while 循环内使用 free

这样解决

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

#include <readline/readline.h>
#include <readline/history.h>

int main()
{
    char *buf;
    char command[32];
    char name[32];

    while((buf = readline("\n"))!=NULL)
    {
        char *pointer;
        if (strcmp(buf,"exit")==0)
            break;

        printf("%s\n",buf);

        pointer = strtok(buf, " ");
        if (pointer != NULL)
        {
            strcpy(command, pointer);
            /* Don't print poitner otherwise since it is unintialized */
            printf("%s\n", pointer);
        }

        /* subsequent calls to strtok must have first argument NULL */
        pointer = strtok(NULL, " ");
        if (pointer != NULL)
        {
            strcpy(name, pointer);
            printf("%s\n", pointer);
        }

        if (buf != NULL) // this is never FALSE because of the while condition
            add_history(buf);
        free(buf);
    }
    return 0;
}

您还必须确保commandname 足够大以适应产生的搅拌。

【讨论】:

  • 仍然出现分段错误。
  • 我正在尝试阅读这个确切的文本:“hi mate.txt”。它工作得很好,但是在第二个输入上它给了我分段错误。
  • @aNNgeL0 您尝试阅读的文本无关紧要,需要注意的一点是您的程序将永远运行,您必须在 while 循环中添加一个条件,以便在用户输入给定字符串时停止比如quit 什么的。
  • 作为一个魅力。谢谢 iharob 。我有一个stop condtion,但没有在这里显示。为什么它不能与那个指针一起工作?我正在阅读“hi mate.txt”,然后是“hi”,然后它给了我分段错误。
  • @aNNgeL0 问题是strcpy 不能处理NULL 参数,您必须传递非NULL 参数。对于while 部分中的free,只需在终端中输入man readline 并阅读手册即可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 2021-06-03
相关资源
最近更新 更多