Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C calling free on not allocated memory

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;
}
  1. Is any possibility that this program will ever crash ?
  2. Should I always make such a if (c) verification before I call free on char* ?
  3. why without c=NULL free is called ?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is any possibility that this program will ever crash ?

  1. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading