How to return local array in C++?

I would suggest std::vector<char>:

std::vector<char> recvmsg()
{
    std::vector<char> buffer(1024);
    //..
    return buffer;
}
int main()
{
    std::vector<char> reply = recvmsg();
}

And then if you ever need char* in your code, then you can use &reply[0] anytime you want. For example,

void f(const char* data, size_t size) {}

f(&reply[0], reply.size());

And you're done. That means, if you're using C API, then you can still use std::vector, as you can pass &reply[0] to the C API (as shown above), and reply to C++ API.

The bottomline is : avoid using new as much as possible. If you use new, then you've to manage it yourself, and you've to delete when you don't need it.


You need to dynamically allocate your char array:

char *recvmsg(){
   char* buffer = new char[1024];
   return buffer;
}

for C++ and

char *recvmsg(){
   char* buffer = malloc(1024);
   return buffer;
}

for C.

What happens is, without dynamic allocation, your variable will reside on the function's stack and will therefore be destroyed on exit. That's why you get the warning. Allocating it on the heap prevents this, but you will have to be careful and free the memory once done with it via delete[].


The warning message is correct. You're returning the address of a local array which disappears after the function returns.

You can do this using dynamic memory allocation:

char *recvmsg(){
    char *buffer = (char*)malloc(1024);
    return buffer;
}

The catch is that you need to make sure you free() the pointer later on to avoid a memory leak.

Alternatively, you can pass the buffer into the function.

void recvmsg(char *buffer,int buffer_size){
    //  write to buffer
}

void main(){
    char buffer[1024];
    recvmsg(buffer,1024);
}

This avoids the need for a memory allocation. This is actually the preferred way to do it.