从函数返回局部变量 [英] Returning local variable from a function
问题描述
在下面的代码中,我返回一个指向在函数内部本地创建的 char
数组的指针。因此,当返回值分配给 y
时,它应该都是垃圾。当我打印%10s
或%100s
时,这似乎成立。但是当我打印%1000s
时,我得到的输出似乎让我感到困惑。
#include< stdio.h>
char * get()
{
char x [1000];
int i = 0; $;
for(; i <999; ++ i)
{
x [i] ='A';
}
x [999] ='\0';
printf(%1000s\\\
,x);
return x;
int main()
{
char * y = get();
printf(去打印\ n);
printf(%1000s\\\
,y);
}
输出为
主要是巧合)
函数正在访问用于创建本地函数char数组的相同内存位置,还是更具体一些?
之后,没有任何保证。
p>换句话说, printf(%1000s \\\
# #语句不能被对齐。它是,是。未定义。
,y);
FWIW,一旦 get()
函数执行完成后,为该函数分配的堆栈空间为销毁,并可通过任何其他功能使用(如果需要)。但是,也许你正在对物理内存的部分进行未经授权的输入,但没有任何确定。
## - 或者, printf(%10s\\\
, y); 或 printf(%100s\\\
,无论哪里
,y); y
被访问。
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?
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.
这篇关于从函数返回局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!