I am making an array with a linked list in it and I am trying to get rid of memory leaks and uninitialised values. Valgrind reports
" Conditional jump or move depends on uninitialised value(s) "
Does anyone know why this is?
Here is my code:
#include<iostream>
#include<string>
using namespace std;
struct Item
{
int key;
string value;
Item *next;
};
//array for storing items and lists of items
//- allocate array
//- create a linked list at array index if needed
Item **items = new Item*[3];
void add_item(int key, string value, int index)
{
//create new item
Item *it = new Item;
it->key = key;
it->value = value;
it->next = NULL;
//if there are no items at location
if(items[index] == NULL)
items[index] = it;
//if there is, iterate through linked list and add item at end
else
{
Item* curr = items[index]; //start of linked list
while(curr->next != NULL)
curr = curr->next;
curr->next = it;
}
}
int main()
{
Item *curr;
add_item(1, "Happy", 0);
add_item(2, "Sad", 0);
add_item(3, "Laughing", 1);
add_item(4, "Angry", 2);
for(int i=0; i<3; i )
{
curr = items[i];
while(curr != NULL)
{
cout<<curr->key<<" "<<curr->value;
curr = curr->next;
if(curr != NULL)
cout<<" --> ";
else
cout<<endl;
}
}
//delete memory
for(int i=0; i<3; i )
{
curr = items[i]; //start of list
//delete linked list starting at array index
while(curr != NULL)
{
Item *temp = curr;
curr = curr->next;
delete temp;
}
}
delete [] items; //delete array
return 0;
}
I have rewritten the program several times and I honestly have no idea why it says that.
CodePudding user response:
Item **items = new Item*[3];
creates an array of 3 uninitialized pointers. So, the check if(items[index] == NULL)
might not be true in the first call. The random value will make the program crash at while(curr->next != NULL)
.
You can fix it by initializing the pointer: Item **items = new Item*[3]();
. The ()
in the end default initializes the values (e.g., to nullptr
in this case).
After that the address sanitizer does not complain anymore: https://godbolt.org/z/3xxzYa4Gs