1

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...

jobrien929
  • 155
  • 1
  • 5

1 Answers1

8
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.

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
  • I wasn't trying to allocate memory for the other structs yet. My intention in this part of the code was to allocate memory for the HashTable struct and the array of pointers. – jobrien929 Nov 13 '11 at 04:06
  • Correct, and as I pointed out above, you're not doing that. You're malloc'ing `index = malloc(sizeof(HashTableT*))` (if you strip away the typedef) which is the size of a pointer not your struct. You then try and use `index->arrayPtr` which is going to be outside the memory you malloc'd. At this point Bad Things happen. – Brian Roach Nov 13 '11 at 04:11
  • Ah, now I understand. Changing it to `sizeof(struct HashTableT)` sorted the error out. Thank you for the help. – jobrien929 Nov 13 '11 at 04:17
  • To add: You can change it to: `index = malloc(sizeof(*index))` and you'll get the correct amount of memory (or, `sizeof(struct HashTableT)` ). – Brian Roach Nov 13 '11 at 04:18
  • No problem. In general, using typedef like that may seem convenient, but it makes things less obvious down the road. – Brian Roach Nov 13 '11 at 04:20