我可以在 C 中 free() 静态和自动变量吗? [英] Can I free() static and automatic variables in C?
问题描述
代码如下:
#include <stdlib.h>
int num = 3; // Static external variable
int *ptr = #
int main(void)
{
int num2 = 4; // Automatic variable
int *ptr2 = &num2;
free(ptr); //Free static variable
free(ptr2); //Free automatic variable
return 0;
}
我尝试编译上面的代码并且它可以工作,我很好奇free()
函数是否能够同时释放静态变量和自动变量?还是基本上什么都不做?
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?
推荐答案
在内存分配函数未返回的指针上调用 free()
(malloc
,calloc
等)导致未定义行为.
你的代码有一个未定义的行为,所以编译器不需要给你任何诊断信息,它可以显示任何行为,它可能工作,或崩溃,或者从字面上做任何事情.
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.
这篇关于我可以在 C 中 free() 静态和自动变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!