Search code examples
c++linuxwindowsmemory-management

Memory Management with returning char* function


Today, without much thought, I wrote a simple function return to a char* based on a switch statement of given enum values. This, however, made me wonder how I could release that memory. What I did was something like this:

char* func()
{
    char* retval = new char[20];
    // Switch blah blah - will always return some value other than NULL since default:
    return retval;
}

I apologize if this is a naive question, but what is the best way to release the memory seeing as I cannot delete the memory after the return and, obviously, if I delete it before, I won't have a returned value. What I was thinking as a viable solution was something like this

void func(char*& in)
{
    // blah blah switch make it do something
}

int main()
{
    char* val = new char[20];

    func(val);
    // Do whatever with func (normally func within a data structure with specific enum set so could run multiple times to change output)

    delete [] val;
    val = NULL;
    return 0;
}

Would anyone have anymore insight on this and/or explanation on which to use?

Regards,
Dennis M.


Solution

  • You could write such functions in pair, like

    Xyz* CreateXyz();
    void DestroyXyz(Xyz *xyz);
    
    
    Abc* NewAbc();
    void DeleteAbc(Abc *abc);
    

    Or you simply can transfer the responsibilty of deleting Xyz/Abc to the clients, i.e ones who call the function must also do delete on the returned object after using it.

    Whatever you choose, make it clear in your documentation how the created object should be destroyed.

    I would prefer pair-functions, especially if there is lot of things to consider before deleting!

    By the way, you should prefer using std::string, instead of char*. Make use of STL as much as you can. They can solve most of your problems! The above advice is for situations where STL doesn't fit! In general, prefer STL!