c - 出现段错误(核心转储)

标签 c

所以我尝试读取行,然后用 strtok 将它们分成两部分。因此,如果我读“nicedog”,它会首先打印我读到的内容,然后在下一行使用 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;
}

最佳答案

您必须检查 strtok 的结果是否为 NULL,这意味着没有找到标记,您将出现段错误

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足够大以适应生成的搅拌。

关于c - 出现段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27531769/

相关文章:

c - C中对象的指针矩阵

C、Windows API在注册表项后创建文件夹结构

用 C 创建一个简单的计算器

c - 在C中是否可以控制函数参数的对齐方式?

c - 在c中打印文件的某一行

c - Linux重定向到C程序-文件读取

c - 如何在C中打印5位/n位数字?

c++ - 当我们对一个int进行运算时,结果是不是暂存在一个int中呢?

C Shell : Redirection and piping working, 但不是输入和输出重定向与 1 个或多个管道的组合

c - C 中的堆栈, 'int' 之前的预期表达式