How to return a string literal from a function

skydoor picture skydoor · Mar 20, 2010 · Viewed 12.6k times · Source

I am always confused about return a string literal or a string from a function. I was told that there might be memory leak because you don't know when the memory will be deleted?

For example, in the code below, how to implement foo() so as to make the output of the code is "Hello World"?

void foo (       )              // you can add parameters here.
{

}

int main ()
{
    char *c;
    foo (    );
    printf ("%s",c);
    return 0;
}

Also, if the return type of foo() is not void, but you can return char*, what should it be?

Answer

GManNickG picture GManNickG · Mar 20, 2010

I'm assuming we cannot modify main. To get your program working without a leak, you need something to have static storage:

void foo(char*& pC)  // reference
{
    static char theString[] = "thingadongdong";

    pC = theString;
}

But really, this isn't very conventional C++ code. You'd be using std::string and std::cout, so you don't have to worry about memory:

std::string foo(void)
{
    return "better thingadongdong";
}

int main(void)
{
    // memory management is done
    std::cout << foo() << std::endl;
}

If you're wondering if something needs to be manually deallocated, it's being done wrong.