创建链表的阵列(为哈希表链)时的valgrind错误 [英] Valgrind Error when creating an array of linked lists (for Hash Table Chaining)

查看:171
本文介绍了创建链表的阵列(为哈希表链)时的valgrind错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为概述,我试图创造C,其中船舶被放置在一个领域的战舰般的游戏。

As an overview, I'm trying to create a battleship-like game in C, where ships are placed on a field.

这是我收到的错误:

Here is the error I am getting:

==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

下面是相关code:

Here is the relevant code:

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;
}

任何人都可以使用此问题的帮助?

Can anyone help with this issue?

推荐答案

您解引用 NULL poitner,你需要让你的指针指向的地方和有效的地方像这样

You are dereferencing a NULL poitner, you need to make your pointer point somewhere and to a valid somewhere, like this

struct field *f = malloc(sizeof(struct field));
if (f == NULL)
   return NULL;
/* ... continue your MakeField() function as it is */

不要忘了免费(F)在调用函数。

顺便说一句,的valgrind 是告诉你,

By the way, valgrind is telling you that

Address 0x8 is not stack'd, malloc'd or (recently) free'd
                           ~~~^~~~

这篇关于创建链表的阵列(为哈希表链)时的valgrind错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆