创建链表数组时出现 Valgrind 错误(对于 Hash Table Chaining)
Valgrind Error when creating an array of linked lists (for Hash Table Chaining)
总的来说,我正在尝试用 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 < numRows; i++){
f->array[i] = temp; <--- VALGRIND ERROR HERE
}
f->count = 0;
return f;
}
谁能帮忙解决这个问题?
您正在取消对 NULL
指针的引用,您需要使指针指向某处并指向有效的某处,就像这样
struct field *f = malloc(sizeof(struct field));
if (f == NULL)
return NULL;
/* ... continue your MakeField() function as it is */
不要忘记在调用函数中free(f)
。
顺便说一下,valgrind 告诉你
Address 0x8 is not stack'd, malloc'd or (recently) free'd
~~~^~~~
总的来说,我正在尝试用 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 < numRows; i++){
f->array[i] = temp; <--- VALGRIND ERROR HERE
}
f->count = 0;
return f;
}
谁能帮忙解决这个问题?
您正在取消对 NULL
指针的引用,您需要使指针指向某处并指向有效的某处,就像这样
struct field *f = malloc(sizeof(struct field));
if (f == NULL)
return NULL;
/* ... continue your MakeField() function as it is */
不要忘记在调用函数中free(f)
。
顺便说一下,valgrind 告诉你
Address 0x8 is not stack'd, malloc'd or (recently) free'd
~~~^~~~