Skip to content
Advertisement

valgrind Address 0x421688c is 0 bytes after a block of size 4 alloc’d for linked list having integer data

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 ” 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?

Advertisement

Answer

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”

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement