简体   繁体   中英

Valgrind invalid write error with array of pointers to structs

I'm getting an error (well, a ton of errors actually) from valgrind that I'm having trouble sorting out.

I'm using this code to declare a struct:

struct HashTableT {

HashFuncT hashFunc;
// array of SortedList's
SortedListPtr* arrayPtr;
};

typedef struct HashTableT* HashTable;

arrayPtr is meant to be a pointer to an array of pointers to other structs. Then allocating memory for it later with this:

HashTable index;
index = malloc(sizeof(HashTable));
memcheck(index);
index->hashFunc = func;
index->arrayPtr = malloc(sizeof(SortedListPtr) * size);
memcheck(index->arrayPtr);
// initialize array
int i;
for (i = 0; i < size; i++) {
    index->arrayPtr[i] = NULL;
}
return index;

Valgrind is giving me this error:

==18735== Invalid write of size 4
==18735==    at 0x80497F1: HTCreate (chainedhash.c:35)
==18735==    by 0x8049727: main (main.c:457)
==18735==  Address 0x402e02c is 0 bytes after a block of size 4 alloc'd
==18735==    at 0x4005B83: malloc (vg_replace_malloc.c:195)
==18735==    by 0x804979B: HTCreate (chainedhash.c:32)
==18735==    by 0x8049727: main (main.c:457)

Line 35 is the one with the malloc statement. It's seems to me that I'm allocating, not writing so the error is confusing me and I can't figure out what to do about it. Any help is appreciated.

Thanks...

index = malloc(sizeof(HashTable));

Malloc's enough memory for a pointer , not your struct.

This also illustrates why typedefs that hide the type like this make things confusing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM