Valgrind Error when creating an array of linked lists (for Hash Table Chaining)

回眸只為那壹抹淺笑 提交于 2020-01-17 06:17:08

问题


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

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?


回答1:


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 */

don't forget to free(f) in the caller function.

By the way, valgrind is telling you that

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


来源:https://stackoverflow.com/questions/28995317/valgrind-error-when-creating-an-array-of-linked-lists-for-hash-table-chaining

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!