Can I free() static and automatic variables in C?

caramel1995 picture caramel1995 · May 23, 2012 · Viewed 12.1k times · Source

The code is as follow :

#include <stdlib.h>

int num = 3;   // Static external variable
int *ptr = &num;

int main(void)
{
 int num2 = 4;  // Automatic variable
 int *ptr2 = &num2;

 free(ptr);  //Free static variable
 free(ptr2); //Free automatic variable

 return 0; 
}

I try to compile the above code and it works, I'm curious does the free() function able to free both the static variable and also automatic variable? Or basically it does nothing?

Answer

Alok Save picture Alok Save · May 23, 2012

Calling free() on a pointer not returned by memory allocating functions(malloc,calloc etc) causes Undefined Behavior.
Your code has an Undefined Behavior, So the compiler does not need to give you any diagnostic of it and it can show any behavior, it might work, or crash, or literally do anything.

Just avoid writing code which causes an Undefined Behavior is the only solution.