Returning local variable from a function [duplicate]

孤者浪人 提交于 2019-12-12 02:59:21

问题


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

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?


回答1:


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.



来源:https://stackoverflow.com/questions/30523611/returning-local-variable-from-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!