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

1

5

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?

Diplococcus answered 2/2, 2017 at 4:16 Comment(3)
Those are identical, the compiler probably generates the same codeDiscover
@DavidBowling Which was actually what I was about to ask about. I understand that arrays and pointers often overlap in behavior, but would this be a situation where assigning to an array (i.e. const char str[]) versus a pointer results in issues? Would the array assignment be automatic storage?Diplococcus
Related: https://mcmap.net/q/23892/-what-is-the-difference-between-char-s-and-char-s/694576Overlap
F
8

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.

Facet answered 2/2, 2017 at 5:0 Comment(1)
I would like to add that local (auto) variables are allocated in the stack, which goes away upon return. So in the first snippet, a local pointer goes away, not the data it points to. In the second snippet the string itself goes away.Explain

© 2022 - 2024 — McMap. All rights reserved.