In the distribution code for Speller in pset5, they include this line in dictionary.c

// Hash table

node *table[N]; 

Should I set every element in the array to NULL, because they are pointers? (the instructors are always saying to set pointers to NULL if you are not initializing them to something meaningful at declaration). Do they not do this in the distribution code because N is set to 0 until we decide on the new length for the hash table?


You should ALWAYS initialize pointers. Unless you're immediately allocating memory to them and setting them to a legitimate address, you should initialize them by setting them to NULL.

Note that if the pointer or array is created as a global, it can't be assigned any value when declared. The assignment must be done inside main or inside a function. In this case, it should be done at the first opportunity, or the first place that the globals are uses.

The reason is simple. When a pointer (a var or an array of pointers) is declared, it is NOT automatically set to any value. The pointer will contain whatever garbage data is in the physical memory that is given to the var to store the pointer's contents. That means that it could be anything. It could be zero (memory that hasn't been used since the computer was started). It could be a random memory address that's invalid, which will throw an error. Worst case is that it could contain a random memory address that's actually a valid memory address in the current program's memory space, which if used, could corrupt the program that's running.

ALWAYS start by setting a pointer to NULL unless it's immediately assigned a valid address through a malloc or calloc, or by copying an address from another pointer (common when using a temp placeholder, like a cursor.)

Related note:

A common error by new programmers is to malloc memory to a new pointer and then copy an address from another pointer into this new pointer. This discards the newly created memory and causes a memory leak. Instead, the correct method is to set the pointer to NULL instead of using malloc to assign memory.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .