0

In the following code, I return a pointer to a char array that is created locally inside the function. Therefore When the return value is assigned to y, it should all be garbage. This seems to hold true when I print %10s or %100s. But when I print %1000s, I get an output that seems to confound me.

#include <stdio.h>

char* get()
{
  char x[1000] ;

  int i = 0;
  for(; i < 999; ++i)
  {
    x[i] = 'A';
  }

  x[999] = '\0';

  printf("%1000s\n",x);

  return x;
  }

  int main()
  {
    char* y = get();
    printf("Going to print\n");
    printf("%1000s\n",y);
  }

The output is enter image description here

Is it a coincidence that the main() function is accessing the same memory location that was used to create the local function char array or is it something more concrete?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Pranav Kapoor
  • 1,171
  • 3
  • 13
  • 32
  • 4
    Any assumptions you make upon invoking undefined behavior are meaningless. That is the very nature of undefined behavior; there is *no definition*. Therefore, the very premise you started with "it should all be garbage" is itself grasping a leap of faith. See http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794 – WhozCraig May 29 '15 at 07:31
  • Why not, `char x[1000] = {0};` then declare `char *get (char *x)` and finally call with `char *y = get (x);` – David C. Rankin May 29 '15 at 07:41

1 Answers1

2

See, once you use the return value of get(), you're facing undefined behaviour.

After that, nothing is guranteed.

In other words, the output of printf("%1000s\n",y);## statement cannot be justified. It is, what it is. Undefined.

FWIW, once the get()function has finsihed execution, the stack space allocated for that function is destroyed and available for usage (if required) by any other function. Maybe you're making unauthorized entry into that part of the physical memory, nothing certain, though.


## - or, printf("%10s\n",y); or printf("%100s\n",y);, whatever, wherever y is accessed.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261