-2

I have a main function that has to receive a string.

main()
{
    char *c = fun();
}

char* fun()
{
    char a[] = "hello";
    return a;
}

The problem is that if I return string of lenght 3 or less, then everything is good. If I return string of length > 3, then I receive garbage value along with the string. Why is that ?

Rash
  • 7,677
  • 1
  • 53
  • 74

4 Answers4

3

You return a pointer to a local variable. The variable is stack-allocated, and it is destroyed when the function exits. Using such pointer is undefined behaviour.

nullptr
  • 11,008
  • 1
  • 23
  • 18
1
char* fun()
{
    char a[] = "hello";
    return a;
}

Array a has automatic storage duration. At the end of the function the array object a is destroyed. This means the pointer becomes invalid at the exit of the function and any use of it is undefined behavior.

ouah
  • 142,963
  • 15
  • 272
  • 331
1

You are returning an automatic variable, which is a big no-no. That it works at all is an accident of the implementation.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

The variable a is local to fun(), and so goes out of scope (and out of existence) when you return. The fact that is works for any case is pure luck. You could make a static, or dynamically allocated, or fix it in ohter ways.

Lee Daniel Crocker
  • 12,927
  • 3
  • 29
  • 55