创建链表列表时出现Valgrind错误(对于哈希表链接)

时间:2015-03-11 19:10:41

标签: c linked-list 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 < numRows; i++){
        f->array[i] = temp; <--- VALGRIND ERROR HERE
    }

    f->count = 0;
    return f;
}

任何人都可以帮忙解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

你正在取消引用一个NULL poitner,你需要把你的指针指向某个地方并且某个地方有效,就像这样

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
                           ~~~^~~~