Search code examples
cpointersnullallocationrealloc

Why NULL ing pointer before using it in realloc function?


If i do the following with malloc

HashTableEntry *util = malloc(sizeof(HashTableEntry) * T->capacity);

all works well. However if i do the following with realloc

HashTableEntry *util = realloc(util, sizeof(HashTableEntry) * T->capacity);

realloc returns NULL. I also get a warning by gcc, saying that i haven't initialized util before using it.

But, the following works perfectly well, like malloc

HashTableEntry *util = NULL;
util = realloc(util, sizeof(HashTableEntry) * T->capacity);

My question is why?

What i believe is happening is that, in all cases, i am creating a pointer and assigning to it the starting address of a block of heap memory i am allocating. Am i wrong somewhere?


Solution

  • In general, functions look at the values of their arguments and use the values to do something, so it's important to pass a specific value instead of something random or unspecified. When you write HashTableEntry *util = realloc(util, sizeof(HashTableEntry) * T->capacity);, you haven't told the compiler what value to put in the util variable when it calls the realloc function, so you'll probably get undefined behavior, which is bad.