Search code examples
carraysinitializationimplicit-conversionstring-literals

C: do all string literals have static storage duration?


I've been reading in various sources that string literals remain in memory for the whole lifetime of the program. In that case, what is the difference between those two functions

char *f1() { return "hello"; }
char *f2() {
   char str[] = "hello";
   return str;
}

While f1 compiles fine, f2 complains that I'm returning stack allocated data. What happens here?

  • if the str points to the actual string literal (which has static duration), why do I get an error?
  • if the string literal is copied to the local variable str, where does the original string literal go? does it remain in memory with no reference to it?

Solution

  • I've been reading in various sources that string literals remain in memory for the whole lifetime of the program.

    Yes.

    In that case, what is the difference between those two functions

    char *f1() { return "hello"; }
    char *f2() {
       char str[] = "hello";
       return str;
    }
    

    f1 returns a pointer to the first element of the array represented by a string literal, which has static storage duration. f2 returns a pointer to the first element of the automatic array str. str has a string literal for an initializer, but it is a separate object.

    While f1 compiles fine, f2 complains that I'm returning stack allocated data. What happens here?

    • if the str points to the actual string literal (which has static duration), why do I get an error?

    It does not. In fact, it itself does not point to anything. It is an array, not a pointer.

    • if the string literal is copied to the local variable str, where does the original string literal go? does it remain in memory with no reference to it?

    C does not specify, but in practice, yes, some representation of the string literal must be stored somewhere in the program, perhaps in the function implementation, because it needs to be used to initialize str anew each time f2 is called.