c++functionreturnchararray

C++ return char* then delete it


So I have this function:

char * func()
{
char * temp = new char[length]; // Length is defined elsewhere
/*
Do some stuff with temp
*/
return temp
}

My problem is I'm not sure whether or not this leaks memory. If so, I don't know how to make it not do that. I thought I could delete it after return, but how would I do that? (Also assuming i can't just delete it outside the function) This function is part of a class. This function's purpose is to return an internal value of the class. A user would use this function. i find it too much to ask that the user deletes the value afterwards. Thanks!


Solution

  • My problem is I'm not sure whether or not this leaks memory.

    This doesn't leak memory, because the pointer to the allocation is returned and thus the ownership is transferred to the caller. If the caller loses the returned pointer value before deleting it, then the caller has leaked memory.

    That said, this is a bad design. You should avoid owning bare pointers. Instead, in this case I recommend returning a vector. This way the vector template will take care of releasing the allocated memory:

    std::vector<char> func()
    {
        std::vector<char>(length) temp;
        /*
        Do some stuff with temp
        */
        return temp;
    }
    

    Alternatively, you could consider using std::string if the array represents text.