0

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;
}
Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43
Nirmal_stack
  • 211
  • 4
  • 15
  • 1
    [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). โ€“ Sourav Ghosh Mar 27 '16 at 20:03

2 Answers2

2

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.
Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

You call free with the value of s after you've incremented it. You need to save the value that you got back from calloc so that you can pass it to free.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278