2

Here is the code changed a bit from this thread:How to return a string in my C code?

#include <stdio.h>
const char * getString();
int main()
{
 printf("hello world\n");
 printf("%s\n", getString());
 printf("%s\n", getString2());
 return 0;

}

const char * getString()
{
 const char *x = "abcstring";
 return x;
}

const char * getString2()
{
 return "abcstring";
}

This looks a bit confusing to me because the memory space which x points to, "abcstring", in getString seems to be on stack instead of on heap. Therefore, the allocated memory for x may be freed at the end of getString. If so, will printf("%s\n", getString()); fail?

And What about printf("%s\n", getString2());?

Community
  • 1
  • 1
Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237
  • 2
    "the x variable in getString seems to be on stack instead of on heap". The `x` variable is an automatic variable (not necessarily on the stack BTW) but not what it is pointing to. – kaylum Jan 11 '16 at 03:29
  • String constants are never on the stack. If they were, it would imply that the runtime environment was dynamically copying them there. It doesn't. They're in static storage. – Tom Karzes Jan 11 '16 at 03:35
  • Returning string literals is safe. Calling the `getString2` function without having first declared its prototype is *not* safe. – dxiv Jan 11 '16 at 03:39

1 Answers1

3

the allocated memory for x may be freed at the end of getString

Yes, but only for x, string literal won't.

String literals have static storage duration, and thus exist in memory for the life of the program.

According to the C++ stardard, $2.13.5/8 String literals [lex.string] (bold by me)

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

And for C string literal,

Then (at stage 7), a terminating null character is added to each string literal, and then each literal initializes an unnamed array with static storage duration and length just enough to contain the contents of the string literal plus one the null terminator.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405