free()跟随指针吗? [英] does free() follow pointers?

查看:79
本文介绍了free()跟随指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定不是,但是也许里面有黑魔法,所以这是我的问题:

I'm sure it doesn't, but maybe there's black magic in it, so here's my question:

如果我有这样的结构:

struct mystr {
    char * strp,
    unsigned int foo,
};

,我为此分配了内存,并希望稍后释放它.我必须要做

and I allocate memory for it and want to release it later. Do I have to do

free(mystr_var->strp);
free(mystr_var);

还是最后一行足够,free()函数是否跟随指针并将它们释放两个指针?

or is the last line enought, does the free() function follow the pointers and free them two?

推荐答案

每个单独分配的内存块都必须单独释放. free()将仅释放指针指向的内存块,并且它不知道该内存的内容.

Every individually allocated block of memory must be freed individually. free() will only free the memory block that the pointer points to and its has no knowledge of what is the content of that memory.

因此,在您的情况下,您首先要释放结构中分配的最里面的内存,然后释放结构指针,这样才能正确地完成操作.

Hence, in your case you are doing it the right way by first freeing the innermost memory allocated in a structure and finally freeing the struct pointer.

如果仅对struct指针执行释放操作,则将释放struct内存. char* strp所拥有的内存在程序生命周期中会成为内存泄漏.

If you just do free on the struct pointer, the struct memory gets freed. The memory held by char* strp, becomes a memory leak in your program lifetime.

这篇关于free()跟随指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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