简体   繁体   English

如何解释这个奇怪的输出? 关于指针和临时变量

[英]How to explain this strange output? About pointer and temporary variable

Who knows why the output is such? 谁知道为什么输出是这样的?
Although it's wrong to use a pointer like that, I would still like to understand why it behaves the way it does. 虽然使用像这样的指针是错误的,但我仍然想知道为什么它的行为方式如此。

int* foo()
{
    int a=9;
    int *p=&a;
    //definitely not right to return a pointer to an invalid varible
    return p;
}
int main(int argc, char* argv[])
{
    int *p=foo();
    cout<<*p<<endl;//9
    cout<<*p<<endl;//2357228
    *p=2;
    cout<<*p<<endl;//2
    (*p)++;
    cout<<*p<<endl;//2357229
    cout<<*p<<endl;//2357228
    cout<<*p<<endl;//2357228
    (*p)++;
    cout<<*p<<endl;//2357229
    cout<<*p<<endl;//2357228

    return 0;

}

Returning a pointer/reference to a variable local to an function results in Undefined Behavior . 将指针/引用返回到函数的本地变量会导致未定义的行为 A local/automatic variable is guaranteed to be alive and valid only in the scope( { , } ) in which it is defined not beyond that scope. 保证本地/自动变量是活动的,仅在范围( {} )中有效,在该范围内定义它不超出该范围。

Undefined behavior means that the program can show any behavior and it is allowed to do so by the C/C++ standards.It is meaningless to try to find reasoning of observed behavior after Undefined behavior has occured because this behavior may/may not be consistent or cannot be relied upon. 未定义的行为意味着程序可以显示任何行为,并且允许通过C / C ++标准执行此操作。尝试在发生未定义行为后查找观察到的行为的推理是没有意义的,因为此行为可能/可能不一致或者不能依赖。

On a bright side any good commercial compiler will provide you warning about such a code. 从好的方面来说,任何优秀的商业编译器都会为您提供有关此类代码的警告。

Although it's wrong to use a pointer like that, I would still like to understand why it behaves the way it does. 虽然使用像这样的指针是错误的,但我仍然想知道为什么它的行为方式如此。

Because p is left pointing at a location in stack memory that keeps getting written over by cout's << method. 因为p指向堆栈内存中的一个位置,不断被cout的<<方法写入。 Every time you use cout, the value of p may change. 每次使用cout时,p的值都可能会改变。

Code like this is dangerous as it can corrupt the stack and cause your program to crash. 像这样的代码是危险的,因为它可以破坏堆栈并导致程序崩溃。

What you need to remember is that a and p are both scope level variables. 你需要记住的是a和p都是范围级变量。 Thus, returning the address of a variable that only exists in the stack (but is not dynamically allocated on the heap) is undefined behavior. 因此,返回仅存在于堆栈中的变量的地址(但未在堆上动态分配)是未定义的行为。 Since we no longer know what gets written to there once it's left that address space. 因为一旦离开那个地址空间,我们就不再知道写到那里的东西了。 Ergo, returning a pointer to a local variable is undefined behavior. 因此,返回指向局部变量的指针是未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM