0

Recently I came across a small issue, which bothered me for quite a while but came across some explanation to it. Though it still is a bit confusing.

char *getString()
{
    char *str = "Print Me!";
    return str;
}

int main()
{
   printf("%s", getString());
   getchar();
   return 0;
}

Gives output as : Print Me!

Although

  char *getString()
 {
     char str[] = "Print Me!";    
     return str;
  }
 int main()
{
    printf("%s", getString());
    getchar();
}

Gives a garbage value. Why is it so.

trincot
  • 317,000
  • 35
  • 244
  • 286
Quick Silver
  • 435
  • 2
  • 8
  • 17

1 Answers1

2

Here:

char *getString()
{
    char str[] = "Print Me!";    
    return str;
}

You are returning an object with automatic storage duration. The lifetime of the object is the block where it is declared. So after the function is returning, your object is destroyed and trying to access invokes undefined behavior.

But here:

char *getString()
{
    char *str = "Print Me!";
    return str;
}

str pointer points to a string literal and string literals have static storage duration. The lifetime of an object with static storage duration is the entire lifetime of the program. Accessing the string literal after the function returns is then perfectly defined.

ouah
  • 142,963
  • 15
  • 272
  • 331