我可以免费C()静态和自动变量? [英] Can I free() static and automatic variables in C?

查看:127
本文介绍了我可以免费C()静态和自动变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在code是如下:

#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; 
}

我尝试编译上面code和它的作品,我很好奇是否免费()功能能够释放静态变量,也都自动变量?或基本什么也不做?

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?

推荐答案

调用免费()上没有内存分配函数(返回一个指针的malloc 释放calloc 等)引起的未定义行为。结果
您code具有不确定的行为,所以编译器不需要给你任何诊断的它,它可以显示任何行为,它可能工作,或崩溃,或从字面上做任何事情。

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.

只要避免写code这会导致不确定的行为是唯一的解决方案。

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

这篇关于我可以免费C()静态和自动变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆