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

ぃ、小莉子 提交于 2019-12-17 20:49:47

问题


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?


回答1:


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.




回答2:


You shouldn't do that. free is only used for memory dynamically allocated from heap by malloc family of functions.

Memory for num is statically allocated in data segment and can't be released. Memory for num2 is allocated in the main's call stack frame and will be released as soon as main returns.

What actually happens depend on implementation of free. There are usually specific data structures maintained in heap to help malloc/free track the allocated and free memory areas. free expects these data structures to be somewhere around the place its argument points to. An when you pass it a pointer which doesn't point to a malloc-allocated heap area, it'll consider garbage data as some useful information and do some strange things. And you're lucky if the result is just an immediate program crash.



来源:https://stackoverflow.com/questions/10716013/can-i-free-static-and-automatic-variables-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!