为什么以及如何运作 [英] Why and how it works

查看:64
本文介绍了为什么以及如何运作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看代码,在此代码中,我创建了"local"变量,并为其分配了值并返回其地址.而且有效.但是如何. "a"是局部变量,因为函数返回不应释放.还是因为编译器未收集内存而起作用.

Please see the code, in this I have created ''local'' varialbe, assigned value and returns its address. And it works. But how. ''a'' is local varible, as function return should it not get freed. Or it is just working because compiler has not collected the memory.

int * ret()
{
    int a = 10;
    return &a;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int *i = ret();
    cout<<*i;
    return 0;
}



提前谢谢.



Thanks in advance.

推荐答案

去看看
Go look at this thread[^].
You are just lucky that the value hasn''t yet been overwritten.
Try this and see what you get:
int _tmain(int argc, _TCHAR* argv[])
{
    int *i = ret();
    cout<<*i;
    cout<<*i;
    return 0;
}



彼得



Peter


在这时,指向局部变量的指针绝对正确.

指向局部变量的指针将继续指向超出范围的内存.

这可能起作用的原因是偶然的,返回的指针指向的内存仍然没有被覆盖(因为仍然没有将任何内容写入堆栈),因此它可以正常工作.如果将此代码保留在更多代码的中间,那么它肯定会给出错误的结果,甚至可能崩溃.

试试这个

You are absolutely correct at this point of pointer to local variable.

the pointer to a local variable will keep pointing to the memory that will has gone out of scope.

The reason this might be working is by pure chance, the memory that the returned pointer is pointing has still not got anything else overwritten on it(since nothing is written on stack still) and thus it is working. If you keep this code in the middle of more code then it will definitely give incorrect results and it might even crash.

try this for instance

int * ret()
{
    int a = 10;
    return &a;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int *i = ret();
    string s = "some rando, string to test";
    cout<<*i;
    return 0;
}


正如某些人已经正确提到的那样.该变量最终出现在堆栈上,随着您嵌套函数调用的增加,该变量也会增加.函数返回时,堆栈会缩小.嵌套函数调用的深度决定了何时由后续的函数调用覆盖它.

如果局部变量已声明为static int a,则该变量将不会存储在堆栈中.但是,当然,如果您返回指向内部静态变量的指针,您将一炮而红.静态函数变量当然不是多线程安全的.
As some people already have mentioned correctly. The variable ended up on the stack, which grows the more you nest function calls. The stack shrinks when the functions returns. The depth of the nested function calls determines when it will overwritten by function calls that comes after.

If the local variable had been declared static int a, the variable wouldn''t have been stored on the stack. But of course, you will get your punched if you ever return pointers to internal static variables. Static functional variables are of course not multithread safe.


这篇关于为什么以及如何运作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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