-2

I guess its a storage/definition difference but still I cant find a straight explanation of the behaviour. I have a function that returns a locally defined char* in two ways:

//Try 1:
char* printSomething()
{
 char arr[100];
 sprintf(arr, "The data %u", 100);
 return arr;
}

//Try 2:
char* printSomething()
{
 return "The data 100";
}

When I print the result of the first function It displays nothing (C) or garbage (C++) while on the second it prints the correct data. I know I should store the data on the heap in cases like this or define static variable but still, how come the first doesnt work while the second does? and also, can I count on the second way to always work?

antonpuz
  • 3,256
  • 4
  • 25
  • 48

2 Answers2

2

The first is just undefined behavior because arr is released when the function ends, so you're left with a dangling pointer.

The second works because "The data 100" is a string literal with static storage duration, which means it persists throught the lifetime of the program.

The implicit conversion to char* is deprecated though, and changing the contents will result in undefined behavior. I suggest you return const char* or std::string.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • Thank you for your answer, I tried creating a ostringstream then return a string from it and it existed on the calling function, its not string literal as far as i understand so why its still exist? – antonpuz Oct 14 '14 at 15:05
  • @Anton.P it's undefined behavior, please read the linked question. – Luchian Grigore Oct 14 '14 at 15:27
0

In both cases you returning char*

The first you return a pointer to a local array variable, located on the stack, which no longer exists after you exit the function. and may be rewritten.

In the second you returning pointer to a const string, located on the code segment, and it exist as long as the program is running.

SHR
  • 7,940
  • 9
  • 38
  • 57