繁体   English   中英

strncpy 出现分段错误

[英]Segmentation fault with strncpy

编辑:变量名

我正在制作一个链表,当我尝试释放一个节点时,它给了我一个错误。 我跟踪了我的代码,发现当我用这段代码创建一个节点时,我的错误是根深蒂固的。

奇怪的是,如果我分配的字符比我想要的少一个字符,它就会起作用。 此外,它适用于分配“单词”,问题在于“id”。

struct node* makeNewNode (char* word, char* id, int occurrences) {
    //make space for the new node
    struct node* temp = malloc (sizeof(struct node*));

    temp->word = malloc(sizeof(char) * strlen(word) + 1);
    strncpy(temp->word, word, strlen(word));
    temp->word[strlen(word)] = '\0';


    temp->id = malloc(sizeof(char) * strlen(id) + 1);
    strncpy(temp->id, id, strlen(id));
    temp->id[strlen(id)] = '\0';

    //assign the number of occurrences to the argument passed in
    temp->occurrences = occurrences;

    //return the newly created node
    return temp;

}

节点的结构是:

struct node {
        char* word;
        char* id;
        int occurrences;
        struct node* next;
};

我的意思是少一个是有效的:

strncpy(temp->id, id, strlen(id)-1);

但是,这意味着我一直在丢失一个字符。

我试图用 for 循环手动复制字符串,但它也不起作用。 我试过附加一个 '\\0' 字符,但它也不起作用。

如果需要,我可以提供我用来测试的内容

可能的候选人是这一行:

struct node* temp = malloc (sizeof(struct node*));

这创造了足够的空间来存储指向节点指针,而不是节点本身。 sizeof表达式中删除* 或者(以及我编写此代码的方式),如果可以避免,请不要在sizeof表达式中使用类型:

struct node *temp= malloc(sizeof *temp);

其他注意事项:

  1. 正如@VladFeinstein 所提到的,使用strdup而不是你的malloc / strlen / strncpy / \\0舞蹈。

     temp->word = strdup(word); temp->id = strdup(id);
  2. 如果您选择不这样做,请注意您的操作顺序在malloc大小表达式中似乎很混乱:

     temp->word = malloc(sizeof(char) * strlen(word) + 1);

    它仍然是正确的,但只是因为sizeof(char)1 我只想写:

     temp->word = malloc(strlen(word) + 1);

    但是,如果您真的打算将sizeof(char)留在那里,请确保正确地将表达式中的加法括起来。

我们可以在您的代码中查找一个off by 1错误。

或者,您可以将mallocstrncpy的使用替换为对strdup一次调用并添加\\0

暂无
暂无

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

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