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?
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.
It is much better to allocate it to the heap by calling malloc.
You will need to allocate the buffer on heap using malloc
.
buffer
is a local/automatic variable and is not guaranteed to exist after the function returns.Using any such buffer beyond the function scope will result in Undefined Behavior.
Yes. This buffer is a local variable using stack and will be released once you exit the function. Use malloc to allocate a dynamic memory buffer.
In this case, no you cannot. More like you can but you should not do this.
Here the buffer
is created on stack which will be reused.
You can return when you allocate with malloc
or similar functions.
No, you can't return pointers to local variables.
The best way to write such functions is to leave allocation to the caller. The advantages are: 1) the code is independent of the memory allocation method and can be used both with statically and dynamically allocated memory, and 2) keep algorithms and memory allocation separated, so that the algorithms only concern themselves with the main task at hand and don't concern themselves with side-tasks irrelevant to the algorithm itself, such as memory allocation.
This kind of program design is very common (for example it is used by the Windows API).
Example:
void print_buffer (char* buffer, size_t size)
{
snprintf(buffer, size, "%s", "test");
}