3

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?

kylemart
  • 1,156
  • 1
  • 13
  • 25
  • 2
    Those are identical, the compiler probably generates the same code – M.M Feb 02 '17 at 04:18
  • 3
    Those are both fine; what you ought to compare to is `const char str[] = "I literally can't even";` – ad absurdum Feb 02 '17 at 04:20
  • @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? – kylemart Feb 02 '17 at 04:23
  • Related: http://stackoverflow.com/q/1704407/694576 – alk Feb 02 '17 at 08:44

1 Answers1

6

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.

ad absurdum
  • 19,498
  • 5
  • 37
  • 60
  • 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. – linuxfan says Reinstate Monica Feb 02 '17 at 09:01