Reputation: 621
Although there were multiple threads related to
valgrind Address 0x421688c is 0 bytes after a block of size 4 alloc'd
kind of questions, but all were expressed with either strlen, or '\0' related issues and I understand them. I am having with linked list insertion dealing with integers.
void insert_node(lnode **head, int num){
lnode *temp = NULL;
temp = calloc(1, sizeof(lnode *));
if(temp == NULL){
printf("Memory Allocation failed!\n");
return;
}
temp->data = num;
temp->next = NULL;
if(*head == NULL){
*head = temp;
}
else{
temp->next = *head;
*head = temp;
}
}
I did insertion, deletion steps and get summary(showing last few lines of valgrind errors as the errors are at the same place):
> ==3238== 9 errors in context 5 of 5:
> ==3238== Invalid read of size 4
> ==3238== at 0x804873D: display (in /home/skb/santosh_practice/linked_list_progs/single_LL/a.out)
> ==3238== by 0x8048636: main (in /home/skb/santosh_practice/linked_list_progs/single_LL/a.out)
> ==3238== Address 0x42168fc is 0 bytes after a block of size 4 alloc'd
> ==3238== at 0x402C17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
> ==3238== by 0x8048686: insert_node (in /home/skb/santosh_practice/linked_list_progs/single_LL/a.out)
> ==3238== by 0x8048614: main (in /home/skb/santosh_practice/linked_list_progs/single_LL/a.out)
> ==3238==
> ==3238== ERROR
ERROR SUMMARY: 22 errors from 5 contexts (suppressed: 0 from 0)
Please tell me where I am doing wrong?
Upvotes: 0
Views: 20212
Reputation: 50831
You are allocating space for a pointer to lnode
, actually the size of any pointer on your platform (4 bytes on a 32 bit system, 8 bytes on a 64 bit system), but you need to allocate space for the struct lnode
which is the thing the pointer points to.
sizeof(lnode *)
is the size of the pointer (usually 4 bytes on a 32 bit system or 8 bytes on a 64 bit system.sizeof(lnode)
is the size of the struct lnode
which depends on how the struct is defined.Upvotes: 1
Reputation: 2506
Your problem lies in the size that you allocated.
lnode *temp = NULL;
temp = calloc(1, sizeof(lnode *));
It must be
lnode *temp = NULL;
temp = calloc(1, sizeof(lnode));
If your structure take 18 octet in memory, and a pointer take 8 octet, with the first code, you will allocate 8 octet instead of 18, which is insuffisent.
a good trick to never have the wrong type is to do
lnode *temp = NULL;
temp = calloc(1, sizeof(*temp));
Because "temp" is type of "lnode *" and "*temp" is type of "lnode"
Upvotes: 4