繁体   English   中英

出现分段错误(核心已转储)

[英]Getting Segmentation fault (core dumped)

因此,我尝试读取行,然后使用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;
}

您必须检查strtok的结果是否为NULL这意味着找不到任何标记,您将获得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足够大以适合产生的混乱。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM