本文介绍了我可以返回函数创建缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
char * return_buffer()
{
char buffer[1024];
snprintf(buffer, sizeof(buffer), "%s", "test");
return buffer;
}
在功能创建的缓冲区,可我直接返回缓冲区?在函数返回之后,缓冲区会消失吗?
buffer is created in the function, can I return the buffer directly? after the function returns, the buffer would disappear?
推荐答案
您正在创建一个静态分配的缓冲区,这意味着正在在栈上创建它。当函数返回时,它会给你堆栈是不再使用上的一个地址。所以,如果你赚更多的函数调用,数据存储这将可能损坏。
You are creating a statically allocated buffer, which means that it is being created on the stack. When the function returns, it will give you an address on the stack that is no longer in use. So if you make more function calls, the data it stores will likely corrupt.
有更好的通过调用malloc分配给堆。
It is much better to allocate it to the heap by calling malloc.
这篇关于我可以返回函数创建缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!