其他分享
首页 > 其他分享> > C语言 warning:address of stack memory associated with local variable returned

C语言 warning:address of stack memory associated with local variable returned

作者:互联网

C语言被调函数中使用malloc

今天在做题中碰到了如下情况
在字符串拷贝的被调函数中使用数组声明内存时
return后出现如下warning:

warning: address of stack memory associated with local variable 'str' returned
    [-Wreturn-stack-address]
    return str;
           ^~~~

栈区作为动态存储空间
声明为栈区的变量在超出程序块范围后会被自动地释放
Google后发现三种解决方法

0x01

Declare variable(str) as static: static char * str; - this will allocate space for str in the static space and not on the stack.
用到关键字static,将变量声明在静态存储区而不是栈区

0x02

Allocate space in the called function on heap (using malloc, calloc, and friends) and pass the ownership to the caller function, which will have to deallocate this space when not needed anymore (using free).
我采用了此方法并且得到了正确的结果
不过我又又又又发现了问题
如果在一个需要返回值的被调函数中使用了malloc
我应该在什么位置释放申请内存的变量呢?
在return后释放那和没写没有区别
如果在return前释放会不会影响函数的返回呢?(验证后发现没影响。奇怪)
这段知识我掌握的并不好
于是我又Google一下
得到了一些同类问题的回答:
由于程序很简单,虽然在子函数中没有free,确实有内存泄漏的风险,但是整个程序执行完成之后,系统还是会回收malloc申请的str的空间的,因此对于现在的这段程序来说,不会对系统造成负担。子函数到了return,程序就已经结束并返回相关结果了,renturn后面的代码是肯定不会运行了的。
答者还提出了如果非要想free掉,可以这样

0x03

char * function(){
	//子函数片段
	return str;
}
int main(){
	char * p = function();
	//主函数
	free(p);
	return 0;
}

标签:function,return,returned,space,free,static,str,address,associated
来源: https://blog.csdn.net/m0_54045571/article/details/116373896