English 中文(简体)
gcc:利用参考可能获取被销毁的套数变量? [复制]
原标题:gcc: access to destroyed stack variable by using reference possible? [duplicate]
This question already has answers here:
Closed 11 years ago.

Possible Duplicate:
Can a local variable s memory be accessed outside its scope?

考虑以下简单的C++代码:

#include <iostream>

struct Test
{
    Test( int i )
        :   ref( i ),
            ptr( &i ) {}

    int &ref;
    int *ptr;
};

int main()
{
    Test t( 5 );

    std::cout << t.ref << std::endl;
    std::cout << *t.ptr << std::endl;

    return 0;
}

班级测试储存着一个点子,是当地变量的指代器,即生活在 st锁上。 我假定,在从测试建筑商返回后,这片人就会被毁。 但显然情况并非如此。 由于这是该方案的产出:

5
134513968

接触点员的结果是我所期望的:一种随时间变化的随机价值。 但是,参考渠道总是在5个方面——正如当地变量仍然存在一样。

谁能向我解释这种行为? I m在64bitlav使用g++(转化4.6.3)。

Regards, enuhtac

问题回答

When constructing t you get the memory address of where i is stored during construction. When you call std::cout << t.ref there has been no reason for that memory location to be used for something else, so the value is still there.

However it s nothing you can trust. It s undefined behaviour to access that memory location after i goes out of scope.

我先仔细检查了它,但仅仅因为你跳下了 st头,并不意味着内容被压倒或改变,该地址的价值保持不变。 之后添加一些方法,应当改变。

没有保证立即删除当地变量。 它可以保持记忆。 但是,这是不明确的行为,它具有危险。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签