kylemart
kylemart

Reputation: 1276

Is it safe to return const char * that was assigned string literal from function?

I understand this is safe...

const char *get_str_literal() {
    return "I literally can't even";
}

But is this?

const char *get_str_literal() {
    const char *str = "I literally can't even";
    return str;
}

If not, why?

Edit: How does the below snipped differ from the second code snippet above?

const char *get_str_literal() {
    const char str[] = "I literally can't even";
    return str;
}

Does the string literal's contents get copied into automatic array storage? What happens?

Upvotes: 5

Views: 1019

Answers (1)

ad absurdum
ad absurdum

Reputation: 21365

In your second example:

const char *get_str_literal() {
    const char *str = "I literally can't even";
    return str;
}

str is a pointer set to point to the string literal, which has static storage duration. So the pointer that is returned will still point to something, namely the string literal, when execution resumes in the calling function.

In your final example:

const char *get_str_literal() {
    const char str[] = "I literally can't even";
    return str;
}

the character array str[] is initialized with a string literal. After initialization, str[] is an array of chars containing the characters of the string literal up to and including the '\0' terminator. When str is encountered in the return statement, it is converted to a pointer to const char, which is returned to the calling function. But, since str[] has automatic storage duration, it's lifetime will have ended and the pointer will become indeterminate, leading to undefined behavior.

Upvotes: 8

Related Questions