局部变量的地址可以在返回指针的函数preserved [英] Can local variables address be preserved in functions returning pointers

查看:105
本文介绍了局部变量的地址可以在返回指针的函数preserved的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>

int* a(int* b){
 int a = 20;
 printf("\n  \n");
 if(a == 20){
  printf("\n return from if a : 0x%x \n",a);
  return &a;
 }
 else{
  printf("\n returning from else b : 0x%x\n",b);
  return b;
 }
}

int main(){
 int n = 10;
 int *k,*m;
 k = &n;
 m = a(k);
 printf("\n m ; 0x%x m : %d \n",m,*m);
 return 0;
}

在这里,我返回函数返回指针的局部变量。在函数退出所有的变量将贝雷从堆栈存储器感动,但如何做功能仍preserves在地址A的价值和打印数据?

Here i'm returning the local variable of the function returning pointer. During function exit all the variables will bere moved from the stack memory , but how does the function still preserves the value at the address 'a' and prints the data ?

O / P:

 return from if a : 0xbfd8cf14

 m ; 0xbfd8cf14 m : 20

的地址被保持在指针m和它正确打印的值。我试图改变没有不同的。

The address is retained in the pointer m and it prints the value correctly. I tried changing different no's.

推荐答案

您可以通过声明静态int类型的= -1使返回值可靠; 这将让 A 坚持你从函数返回即使......但是这在很多​​情况下,一个非常糟糕的主意......特别是如果你将要多线程的。

You could make the return value "reliable" by declaring static int a = -1; which would make a persist even after you return from the function... but that's a really bad idea in many cases... especially if you are going to be multi-threaded.

这是说...指针返回到一个临时(局部)变量要在运行时造成严重破坏。所以,你再也不想这样做...你需要做一个静态本地或找到更好的方法来处理它。

That said... returning a pointer to a temporary (local) variable is going to cause havoc at runtime. So, you don't ever want to do that... you need to make it a static local or find a better way to deal with it.

拓展您的修改后的回答:如果您分配了 1 A 作为一个局部变量,你'重实际存储 1 在位置堆栈和&放大器;一个指向该​​位置。当你从函数返回,堆栈不被破坏,但现在的行为是不确定的,因为虽然地址是一个有效的指针,在该地址的内容很可能被修改......例如,如果你调用另一个函数,将数据推入堆栈且/或声明局部变量,它们很可能覆盖您预期的价值。另外,谁知道优化器可能注入了什么疯狂。所以......它的可能的工作的如果的你碰巧读之前,它别的渣土的价值......但你不能保证它会工作,它往往会有所不同从一个实施到另一

Extending the answer after your edits: when you assign -1 to a as a local variable, you're actually storing -1 at a location on the stack and &a points to that location. When you return from the function, the stack is not destroyed, but the behavior is now undefined because while the address is a valid pointer, the content at that address may well have been modified... for example, if you call another function that pushes data on the stack and/or declares local variables, they may well have overwritten the value you expected. In addition, who knows what madness the optimizer may have injected. So... it might work if you happen to read the value before anything else mucks with it... but you have no guarantee it will work and it will often vary from one implementation to another.

这篇关于局部变量的地址可以在返回指针的函数preserved的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆