3

I am confused as to how we are able to return strings from function.

char* someFunction()
{
  return "Hello, World"
}

Shouldn't the above return statement throw "function returns address of local variable" and how is it different from the function:

char* newFunction()
{
  char temp[] = "Hello, World";
  return temp;
}

which in fact does give the warning mentioned above.

Pratt
  • 851
  • 2
  • 10
  • 16
  • 1
    You need to make the first case `const char*` really – Flexo Jun 18 '12 at 17:51
  • Note that the word "throw" often refers to an exception handling mechanism... That's probably not what you meant, given that C does not have any innate support for such. – Kaganar Jun 18 '12 at 17:51
  • 2
    There's an existing [question](http://stackoverflow.com/q/1704407/168175) that covers the critical difference between the two cases. – Flexo Jun 18 '12 at 17:56

2 Answers2

5

In the first case, the string lives in constant readonly memory at a fixed address for all time. In the second case, the string is put locally on the stack, and so is temporary.

TJD
  • 11,800
  • 1
  • 26
  • 34
  • I didn't completely understand what you said. Are you saying that since it is a string constant the compiler would have already allocated memory for it during compile-time and therefore not cause any problem. – Pratt Jun 18 '12 at 18:00
  • Yes, the compiler is statically allocating the string at a fixed global address. I mean the same thing as the accepted answer from ouah. – TJD Jun 18 '12 at 18:30
1

String literals have static storage duration. You can return a pointer to a string and then access the string, it is perfectly valid and defined behavior.

char* someFunction()
{
  return "Hello, World"
}

In the below case, you are returning a pointer to a string with automatic storage duration. An object with automatic storage duration is destroyed after exiting the block where it is defined. So accessing it after the function returns is undefined behavior.

char* newFunction()
{
  char temp[] = "Hello, World";
  return temp;
}
ouah
  • 142,963
  • 15
  • 272
  • 331