编辑:变量名
我正在创建一个链接列表,当我试图释放一个节点时,它会给我一个错误。我跟踪我的代码,发现当我用这个代码创建一个节点时,我的错误是根深蒂固的。
奇怪的是,如果我分配的比我想要的少一个字符,它就会起作用。此外,它可以很好地分配"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‘字符,但它也不起作用。
如果需要的话,我可以提供我用来测试这个的
发布于 2019-11-25 04:16:04
可能的候选人是这一行:
struct node* temp = malloc (sizeof(struct node*));
它创建了足够的空间来存储指向节点的指针,而不是节点本身。从*
表达式中删除sizeof
。或者(以及我编写这段代码的方式),如果可以避免的话,就不要在sizeof
表达式中使用类型:
struct node *temp= malloc(sizeof *temp);
其他说明:
@VladFeinstein提到的malloc
/strlen
/strncpy
/\0
strdup
代替您的strdup
舞蹈。temp->word = strdup(word);temp->id = strdup(id);
malloc
大小表达式中,您的操作顺序似乎很混乱:temp->word = malloc(sizeof(char) * strlen(word) + 1);
它仍然是正确的,但这只是因为sizeof(char)
是1
。我只想写:
temp->word = malloc(strlen(word) + 1);
但是,如果您真的打算将sizeof(char)
留在这里,请确保正确地插入表达式中的加法。
发布于 2019-11-25 04:14:19
我们可以在代码中查找off by 1
错误。
或者,您可以将malloc
、strncpy
和添加\0
的用法替换为对strdup
的一个调用。
https://stackoverflow.com/questions/59025128
复制相似问题