释放全局变量 [英] Freeing global variable

查看:142
本文介绍了释放全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假如我有一个包含一个大的结构的全局变量:

Suppose I have a global variable that contains a large structure:

typedef struct {
    char Big[1024]
} LARGE;

static LARGE x;

void main()
{
     free(x);
}

我可以安全地从主调用free(x)的时候我不需要它了?

Can I safely call free(x) from main when I dont need it anymore?

推荐答案

没有。你没有动态分配 X 所以不需要(也不能)释放它。

No. You didn't dynamically allocate x so don't need to (and cannot) free it.

如果你绝对需要你的程序退出前释放内存,声明指针作为全球性的,它分配上的需求,使用的malloc 释放calloc ,那么免费它,当你与结构完成。

If you absolutely need to free the memory before your program exits, declare a pointer as global, allocate it on demand, using malloc or calloc, then free it when you're finished with the structure.

static LARGE* x;

void main()
{
    x = malloc(sizeof(*x));
    // use x
    free(x);
}

这篇关于释放全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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