创建链接列表数组时出现Valgrind错误(对于哈希表链接)
作为概述,我正在尝试在C中创建一个类似战舰的游戏,船只被放置在一个场地上。
这是我得到的错误:
==11147== Invalid write of size 8 ==11147== at 0x400786: MakeField (battleship.c:34) ==11147== Address 0x8 is not stack'd, malloc'd or (recently) free'd
这是相关的代码:
struct piece{ int x; int y; int direction; int length; char name; }; struct node{ struct piece boat; struct node *next; }; struct field{ int numBoats; struct node *array[numRows]; }; struct field *MakeField(void){ struct field *f = NULL; struct node *temp = NULL; for(int i = 0; i array[i] = temp; count = 0; return f; }
有人可以帮忙解决这个问题吗?
您正在取消引用NULL
poitner,您需要将指针指向某处并在某处有效,就像这样
struct field *f = malloc(sizeof(struct field)); if (f == NULL) return NULL; /* ... continue your MakeField() function as it is */
不要忘记在呼叫者function中free(f)
。
顺便说一句, valgrind告诉你
Address 0x8 is not stack'd, malloc'd or (recently) free'd ~~~^~~~