Search code examples
cpointersmallocfreecalloc

Program crashing on free() with an invalid pointer message


I don't know,why I am getting this error:

Error in `./prog': free(): invalid pointer: 0x0941600b

While executing this code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int test;   
    scanf("%d",&test);
    while(test)
    {
        char *s;
        int count=0;
        s=(char *)calloc(10000,sizeof(char));
        scanf("%s",s);
        while(*s)
        {
            if(*s=='W')
                count++;
            s++;
        } 
        printf("%d\n",count);  
        free(s);
        test--;
    }
    return 0;
}

Solution

  • In you code, you first did

     s++;  //moving the actually returned pointer
    

    and then, you tried

     free(s);  //pass the changed pointer
    

    So, once you're not passing the same pointer which was returned by calloc(). This invokes undefined behavior.

    To add, quoting the C11 standard, chapter §7.22.3.3

    [...] if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

    so the s++ modifies the original pointer which is not the same anymore which was returned by calloc() and passing the same to free() invokes UB. You need to keep a copy of the original pointer to pass that to free() later.

    That said,

    1. Please see this discussion on why not to cast the return value of malloc() and family in C..
    2. You should always check the return value of calloc() and family before using the returned value to avoid deferefencing of NULL pointer in case the function call failed.