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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.