一个非常简单的返回局部字符数组的C语言程序, 请问其输出结果?

以下是该无聊的程序:

#include <stdio.h>
#include <string.h>

char* get_str()
{
    int x[10];
    char str[] = "hello world! long long long long long long long!!!";
    return str;
}

int main()
{
    char a[256];
    char* str = get_str();
    strcpy(a, str);
    printf("str=%s ", a);
    return 0;
}

问程序的程序输出结果是啥?

我相信大多数人都会觉得这个题有点BUG, 返回了局部数组, 程序无法预料. 事实确实是这样.

但就算事实就摆在眼前, 你仍然可以拿编译器试试他们的输出结果:

比如: VS2012 + VC6.0 + GCC4.7 在DEBUG模式下的输出结果均是正确的:

hello world! long long long long long long long!!!

你们知道是什么原因吗? ^^^^

如果你了解一点汇编, 那么你可能知道, 函数返回时可能只是一个简单的add esp,x

如果你只是无脑地认为 "局部数组" 函数返回后就 "消失" 了的话, 我也无法可说了.

2014-06-08 23:27:28 更新:

  哈哈, 无独有偶, 我居然在StackOverflow看到了一篇非常类似的文章 : Can a local variable's memory be accessed outside its scope?

  这个问题得到了微软资深软件工程师 Eric Lippert 的最佳答案.

原文地址:https://www.cnblogs.com/memset/p/C_Language_Returns_Local_Char_Array.html