问题
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