This is my code for a hash table which stores string values.To use Linear probing in my "insert" function, I need to check whether the pointer is NULL at that specific hash value. I Haven't completed my insert function yet, but I am stuck because when I check for if(the_hash_table[n]==NULL) inside the insert function, it does not enter the branch. Before hashing the value if I print "the_hash_table[1]" it prints "faz", but after that step when I print it, it prints some weird characters. Where have I gone wrong?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
creates a hash table of size 10
*/
char** create_hash_table(){
char* the_hash_table[10]; // defines a hash table to store strings
*the_hash_table=malloc(sizeof(char*)*10); // allocates memory in the heap for the hash table
int i;
for(i=0;i<10;i++){ // this loop initializes the string pointers to NULL at the starting point of the hash table
the_hash_table[i]=NULL;
}
return &the_hash_table; // returns the address of the hash table to the main memory
}
/*
this is a method to insert a string into the relevant position of the hash table
*/
void insert(char* the_string,char** the_hash_table){
printf("%s",the_hash_table[1]);
int n=hash(the_string);
printf("%s",the_hash_table[1]);
if(the_hash_table[n] == NULL)
the_hash_table[n]=the_string;
}
You haven't allocated memory correctly.
You define an automatic variable, the_hash_table
as an array of pointers. You allocate some memory and put the pointer to that memory in your array. You immediately overwrite that pointer (and the other elements of the_hash_table
) with null pointers.
Then you return a pointer to the local array, but the array no longer exists once the function exits. It is always wrong to return a pointer to an automatic variable from the function it's defined in.
What you should do is:
char** create_hash_table(void) {
char** the_hash_table = malloc(sizeof(*the_hash_table) * 10);
for (int i = 0; i < 10; ++i) {
the_hash_table[i] = NULL;
}
return the_hash_table;
}
So, the_hash_table
is a local variable that points to the allocated memory. You return its value, which is the address of the allocated memory. Then in main
you would free(the_hash_table)
not free(*the_hash_table)
.
Also, in your hash
function there is no point copying the string: just read the characters from the_string[i]
. Even if there was a point in copying it, the buffer that you create in order to do so is 1 byte too small, it needs to be strlen(the_string)+1
because the length returned by strlen
does not include the 0 byte that terminates the string.