【发布时间】:2020-12-06 08:04:39
【问题描述】:
我正在尝试将新节点添加到我的链表中,但它会给出内存错误
我的结构和全局变量:
typedef struct word word;
struct word
{
char str[256];
word *next;
};
word *head = NULL;
word *cur = NULL;
功能:
int addWord(char * str)
{
word *w = calloc(1, sizeof(w));
if(w == NULL)
{
return 0;
}
strcpy(w->str, str);
if(cur == NULL)
{
cur = w;
head = w;
}
else
{
puts("4");
cur->next = w;
puts("5");
cur = w;
puts("6");
}
return 1;
}
结果是:
...
4
5
6
4
==73913== Invalid write of size 8
==73913== at 0x109425: addWord (in /home/mz37/programming/godaphy/bin/godaphy.out)
==73913== by 0x109696: parseLine (in /home/mz37/programming/godaphy/bin/godaphy.out)
==73913== by 0x109351: main (in /home/mz37/programming/godaphy/bin/godaphy.out)
==73913== Address 0x4a6a880 is 96 bytes inside an unallocated block of size 4,188,096 in arena "client"
==73913==
5
6
我仍在寻找错误,但我还没有找到它
【问题讨论】:
-
又一个无聊的错字:
sizeof(w);->sizeof(*w)。
标签: c pointers data-structures