How to return local array in C++?

user494461 picture user494461 · Oct 14, 2011 · Viewed 57.5k times · Source
char *recvmsg(){
    char buffer[1024];
    return buffer;
}

int main(){
    char *reply = recvmsg();
    .....
}

I get a warning:

warning C4172: returning address of local variable or temporary

Answer

Nawaz picture Nawaz · Oct 14, 2011

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.