2
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?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user1787726
  • 65
  • 1
  • 3
  • [You're correct](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope). You need to allocate some memory dynamically, or get the user to do that and pass in the buffer to use. – chris Oct 31 '12 at 07:03

6 Answers6

3

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.

Kiith Nabaal
  • 366
  • 2
  • 5
  • 16
  • 2
    Just note that "statically allocated" in this case means: allocated with a static array size known at compile time. Not to be confused with the keyword `static` and static storage duration. – Lundin Oct 31 '12 at 07:48
1

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.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

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.

SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85
0

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.

Rohan
  • 52,392
  • 12
  • 90
  • 87
0

This is not possible and may lead to crash. Here the memory is allocated on the stack and once the function returns memory will be freed. If you want to return buffer from a function then you have to allocate memory on the heap. You can use malloc/calloc for this. Read more

CCoder
  • 2,305
  • 19
  • 41
0

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");
}
Lundin
  • 195,001
  • 40
  • 254
  • 396