The part of following code is an implementation of a simple hash lookup algorithm from K&R. lookup searches for s in the table, and returns a pointer to the place where it was found, or NULL if it wasn't there:
struct hashElement *lookup(char *name){
struct hashElement *currentStruct;
int cmp;
for (currentStruct = hashTable[calcIndex(name)]; currentStruct; currentStruct = currentStruct->p)
if (cmp = strcmp(name, currentStruct->name) == 0)
return currentStruct;
return NULL;}
Install uses lookup to determine whether the name being installed is already present:
struct nlist *install(char *name, char *defn)
{
struct nlist *np;
unsigned hashval;
if ((np = lookup(name)) == NULL){
np = (struct nlist *) malloc(sizeof(*np));
...}
...}
If lookup returns NULL, it means that there is no name installed in hash table, and I should allocate memory for new element which type will be nlist.
But, based on this np = (struct nlist *) malloc(sizeof(*np));
*np will allocate memory for NULL if lookup return NULL.
Shouldn't I always allocate memory size for nlist instead of *np?