Why this program doesn’t crash, is it undefined behaviour ?
int main()
{
char* c;
if (c) {
printf("called free\n");
free (c);
}
else {
printf("not called free\n");
}
printf("not crashed\n");
c = strdup("someString");
if (c) {
printf("called free\n");
free(c);
c = NULL; // why is this needed for last if (c)
}
if (c) {
free(c);
}
printf("still not crashed\n");
return 0;
}
- Is any possibility that this program will ever crash ?
- Should I always make such a if (c) verification before I call free on char* ?
- why without c=NULL free is called ?
>Solution :
Is any possibility that this program will ever crash ?
- Yes, there is. Your code invokes undefined behaviour;
behavior, upon use of a nonportable or erroneous program construct or
of erroneous data, for which this International Standard imposes no
requirements.
Anything can happen, and that includes a crash.
Should I always make such a if (c) verification before I call free on
char* ?
No, a call to free() with a NULL pointer constant is a NOP, i.e. no operation is performed. So it’s unnecessary.
why without c=NULL free is called ?
Because the free() function doesn’t set the original pointer to NULL. c is still pointing to the same memory location, but it is invalid for c to access it anymore. Without setting c to NULL, a subsequent call to free() would be freeing already freed memory, which also invokes undefined behaviour.