I have the following test.h
file:
typedef struct node *Node;
struct node {
const char *key;
Node next;
};
typedef struct table_s *Table;
struct table_s {
int n;
Node *arrayOfNodes;
};
And also this test.c
file:
Table new_table() {
Table thisTable = malloc(sizeof(Table));
thisTable->n = 2;
thisTable->arrayOfNodes = malloc(thisTable->n*sizeof(Node));
//this line is inserted here so I can check that calling malloc() like this actuallt work
Node *array = malloc(thisTable->n*sizeof(Node));
return thisTable;
}
int main() {
Table myTable = new_table();
return 0;
}
The program compiles and works, but valgrind.log indicates there are errors:
==8275== Invalid write of size 8
==8275== at 0x40056E: new_table (test.c:8)
==8275== by 0x40043A: main (test.c:18)
==8275== Address 0x5204048 is 0 bytes after a block of size 8 alloc'd
==8275== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==8275== by 0x40055A: new_table (test.c:6)
==8275== by 0x40043A: main (test.c:18)
Why does the malloc() call in line 11 works fine but in line 8 causes this errors? This is making my bigger version of this program to not work with large entries (when n gets bigger).