An uninitialized value was created by heap allocation

I am trying to implement a dictionary of words using a hash table, so I need it to be global, and in one of my header files I declare it

extern node** dictionary; 

Where node is

 typedef struct node { char* word; struct node* next; } node; 

Then in another file in which the functions are defined, I include a header that has a dictionary declaration, and also add at the top

 node** dictionary; 

Then in the function that actually loads the dictionary, I first allocate memory for linked lists that will make a hash table

 bool load(const char* dict_file) { dictionary = malloc(sizeof(node*) * LISTS); FILE* dict = fopen(dict_file, "r"); if(dict == NULL) return false; char buffer[MAX_LEN + 2]; size_dict = 0; while(fgets(buffer, MAX_LEN + 2, dict) != NULL) { node* new_node = malloc(sizeof(node)); int len = strlen(buffer); new_node->word = malloc(sizeof(char) * (len)); //avoid \n for(int i = 0; i < len - 1; i++) new_node->word[i] = buffer[i]; new_node->word[len - 1] = '\0'; new_node->next = NULL; int index = hash(buffer); new_node->next = dictionary[index]; dictionary[index] = new_node; size_dict++; } if (ferror(dict)) { fclose(dict); return false; } fclose(dict); return true; } 

So, the program works fine, I free all the allocated memory for lines and nodes, and when I run valgrind (a debugger that detects memory leaks), it says that memory leaks are impossible, but it says that there is an error An uninitialized value was created heap distribution and redirects me to this exact line, where I allocate memory for the dictionary exact first line of the load function that I wrote above. am i doing wrong? I assume that the way I use dictionary globally is wrong, so can anyone suggest another way to keep it global and avoid this error?

+5
source share
2 answers

The updated code uses an uninitialized pointer:

 dictionary = malloc(sizeof(node*) * LISTS); // .... code that does not change dictionary[i] for any i new_node->next = dictionary[index]; // use uninitialized pointer 

As people have already guessed, this will only work if you previously set all the pointers to NULL before entering this loop:

 dictionary = malloc(sizeof(node*) * LISTS); if ( !dictionary ) return false; for (size_t i = 0; i < LISTS; ++i) dictionary[i] = NULL; 
+7
source

The heap distribution you assign to dictionary uses malloc , which does not initialize the returned bytes. So the dictionary in the code you posted is an array of uninitialized pointers. Presumably, you continue to use these pointers in some way that valgrind knows as an error.

An easy way to fix this is to use calloc instead of malloc because it returns bytes zero to you. Or, use memset for null byte yourself.

+3
source

Source: https://habr.com/ru/post/1209675/


All Articles