Search code examples
c++arrayscallstackchar-pointer

Why do char arrays get lost when returning from a function in C++?


I know that, if we declare variables inside a function without allocating memory for them, they will be lost after the function finishes its job.

The following code prints:

(null)
5
char* getString() 
{ 
  char arr[] = "SomeText";
  return arr;  
}      

int getInt()
{
    int b = 5;
    return b;
}

int main() 
{ 
  printf("%s", getString());
  printf("\n");
  printf("%d", getInt());

  return 0; 
} 

Both arr and b variables are created on the stack, so they both should be destroyed when the functions end. My question is, how come variable b doesn't get lost while variable arr is lost?


Solution

  • A unique and often confusing feature of C (and inherited by C++) is that an array when used in an expression is not treated as a collection of values, but (most of the time) as a pointer to its first element. So, when you return an array from a function, you are returning the address of its first element.

    Dereferencing the address of an object with automatic storage duration that is no longer in scope results in undefined behavior.

    When you return a value from a function, a copy of the value is returned to the caller.

    Thus, when you return an integer, the caller receives a copy of that integer value.

    If the value is a pointer, the copied value is a pointer. If the pointer is pointing to an invalid object, then if the receiver of the pointer tried to dereference the pointer value, it would result in undefined behavior.


    There are 3 exceptions: (1) As an operand to &; (2) As an operand to sizeof; and (3) A string literal used to initialize an array. In C++, there are other exceptions: (4) As an operand of decltype; (5) As the function argument to a reference parameter; (6) An object to initialize a reference variable; ... probably something else I am forgetting...