Search code examples
cpointersreturn-valuestring-literals

Returning content of char * from a function


Recently came across following code which declares a char *p, assigns value such as p="GOOD" and returns return p. Is the return value valid when function call is completed?

const char * get_state(int state)
{
    char *p;

    if (state) {
        p = "GOOD";
    }
    else
    {
        p = "BAD";
    }

    return p;
}

Solution

    • Is the return value valid when function call is completed?

    Yes, because p points at a string literal, a string literal has static storage duration and that means:

    (Section 6.2.4 p3 of the C spec)

    Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

    So the C language guarantees that the strings "GOOD" and "BAD" will be available everywhere in your program and get_state() will just be returning a pointer to one of those memory locations.