gpt4 book ai didi

c - Valgrind 创建链表数组时出错(用于哈希表链接)

转载 作者:行者123 更新时间:2023-11-30 15:22:52 24 4
gpt4 key购买 nike

作为概述,我正在尝试用 C 创建一个类似战舰的游戏,其中船只被放置在一个 field 上。

这是我收到的错误:

==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 - Valgrind 创建链表数组时出错(用于哈希表链接),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28995317/

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