会自动的malloc在函数的最后释放内存? [英] Will malloc automatically free the memory at the end of a function?

查看:254
本文介绍了会自动的malloc在函数的最后释放内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将非常高兴,如果有人可以帮助我理解完全以下codeS之间的差异:

I would be very glad if someone could help me in understanding completely the differences between the following codes:

// Code (1)
void f1 ( void ){
  int * ptr1 = malloc ( sizeof(int) );
}

// Code (2)
void f2 ( void ){
  int * ptr2 = malloc ( sizeof(int) );
  free(ptr2);
}

据我所知,自由的指令是重新分配使用的内存是有用的,但另一方面,我知道,每次我们调用一个函数g,如果这里有被宣布,他们将创造新的变量和克执行后销毁(即释放的,对吧?)。

As far I know, the instruction free is useful for deallocating the used memory, but on the other hand I know that every time we call a function g, if here there are new variables to be declared, they will be created and destroyed (i.e. deallocated, right?) after the execution of g.

结果:

我们需要使用免费code(2)指令,或者是多余的? (但也许建议作出的code更清晰)

do we need to use the instruction free in Code(2), or it is superfluous? (but maybe suggested for making the code more clear)

感谢

PS:你可能也有兴趣帮助我<一个href=\"https://stackoverflow.com/questions/34381232/function-that-creates-variables-with-new-memory-addresses-at-each-calling\">My previous相关的问题。在那里,一些用户建议使用的内存动态分配,我试图理解为什么/如何。

Ps: you may be also interested in helping me with My previous related question. There, some users suggested to use the dynamic allocation of memory, and I am trying to understand why/how to.

推荐答案

没有。 的malloc 不会释放已分配的内存。您需要使用免费来释放分配的块。结果
这也是在程序结束时(功能)分配的内存由系统自动释放,但最好明确释放它的情况。

No. malloc will not free the allocated memory. You need to use free to free the allocated chunk.
It is also the case that at the end of the program (main function) the allocated memory automatically freed by the system, but better to free it explicitly.

永远记住,动态分配的内存的寿命,直到节目结束,如果没有特别释放。

Always remember that the lifetime of dynamically allocated memory is till the end of the program if it is not deallocated specifically.

这篇关于会自动的malloc在函数的最后释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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