user1787726
user1787726

Reputation: 65

Can I return buffer created in functions?

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?

Upvotes: 2

Views: 7048

Answers (6)

Lundin
Lundin

Reputation: 214810

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");
}

Upvotes: 0

CCoder
CCoder

Reputation: 2335

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

Upvotes: 0

Kiith Nabaal
Kiith Nabaal

Reputation: 466

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.

Upvotes: 3

Rohan
Rohan

Reputation: 53386

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.

Upvotes: 0

SomeWittyUsername
SomeWittyUsername

Reputation: 18368

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.

Upvotes: 0

Alok Save
Alok Save

Reputation: 206616

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.

Upvotes: 1

Related Questions