不走出去的这样的范围内释放相关的内存? [英] Does going out of scope like this free the associated memory?
问题描述
我只是想知道,在下面的scenarion,是方法1后释放'STRINGVAR'所使用的内存是做执行?
I was just wondering, in the following scenarion, is the memory used by 'stringvar' freed after method1 is done executing?
// Just some method
void method2(char* str)
{
// Allocate 10 characters for str
str = malloc(10 * sizeof(char));
}
// Just another method
void method1()
{
char* stringvar;
method2(stringvar);
// Is the memory freed hereafter, or do I need to call free()?
}
我问,因为如果我把自由(STRINGVAR)的方法1月底,我得到一个警告,STRINGVAR在里面方法1(这是真的)未初始化。
I ask, because if I put a 'free(stringvar)' at the end of method1, I get a warning that stringvar is unitialized inside method1 (which is true).
推荐答案
没有,内存的不的方法1后释放
,所以你'将有一个内存泄漏。是的,你需要调用免费
您使用的内存中完成了。
No, the memory is not deallocated after method1
, so you'll have a memory leak. Yes, you will need to call free
after you're done using the memory.
您需要一个 指针发送到一个指针的以方法2
如果你想让它分配内存。这是C语言中常见的成语,尤其是当一个函数的返回值是保留整数状态codeS。例如,
You need to send a pointer to a pointer to method2
if you want it to allocate memory. This is a common idiom in C programming, especially when the return value of a function is reserved for integer status codes. For instance,
void method2(char **str) {
*str = (char *)malloc(10);
}
char *stringvar;
method2(&stringvar);
free(stringvar);
这篇关于不走出去的这样的范围内释放相关的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!