Memory Management with returning char* function

Posted by RageD on Stack Overflow See other posts from Stack Overflow or by RageD
Published on 2010-12-26T17:12:29Z Indexed on 2010/12/26 17:54 UTC
Read the original article Hit count: 169

Hello all,

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;
    // 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;

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

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

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

Regards,
Dennis M.

© Stack Overflow or respective owner

Related posts about c++

Related posts about Windows