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;
}
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
orrealloc
, 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,
malloc()
and family in C
..calloc()
and family before using the returned value to avoid deferefencing of NULL pointer in case the function call failed.