gpt4 book ai didi

c - strncpy 的段错误

转载 作者:行者123 更新时间:2023-12-04 10:28:16 24 4
gpt4 key购买 nike

编辑:变量名

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

奇怪的是,如果我分配的字符比我想要的少一个,它就可以工作。此外,它可以很好地分配“word”,问题在于“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) 留在其中,请确保正确地将表达式中的加法括起来。

关于c - strncpy 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59025128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com