why do I get an Invalid read of size 8
My goal is to pass an array of integers to a function that will return a pointer to the last Item
in the linked list and it will fill the array of Item
pointers with pointers for each item created
everything works fine and compiling does not show any errors and running the program does not show any errors as well but when I use valgrind
with it I get the error in valgrind output below
typedef struct Item
{
int num ;
struct Item *next;
}Item;
Item * create_list(int * arr, int len, Item ** lst)
{
Item * tmpItem = malloc(sizeof(Item));
for (int i=0; i < len; i++)
{
lst[i] = tmpItem;
tmpItem->num = arr[i];
if ( i+1!=len )
{
tmpItem->next = malloc(sizeof(Item));
tmpItem = tmpItem->next;
}
else
tmpItem->next = NULL;
}
return tmpItem;
}
void free_lst(Item ** lst, int len)
{
for (int i =0; i < len; i++)
{
free(lst[i]);
}
}
int main()
{
int arr[] = {1,2,3,4,5};
Item * items[sizeof(arr)/sizeof(int)];
Item * tmp = create_list(arr, sizeof(arr)/sizeof(int), items);
free_lst(items, sizeof(arr)/sizeof(int));
printf('%p\n',tmp->next);
}
valgrind output
==12169== Invalid read of size 8
==12169== at 0x109270: main (main.c:26)
==12169== Address 0x4a59228 is 8 bytes inside a block of size 16 free'd
==12169== at 0x483CA3F: free (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==12169== by 0x10939D: free_lst (list.c:45)
==12169== by 0x10926B: main (main.c:24)
==12169== Block was alloc'd at
==12169== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==12169== by 0x10931C: create_list (list.c:24)
==12169== by 0x109209: main (main.c:13)
==12169==
I don't understand why am I getting this error but I guess this is because the last element in the linked list has a null pointer and this causes the last element to be 8 bytes long not 16