为什么是不好的做法,返回一个指针到一个局部变量或参数? [英] Why is it bad practice to return a pointer to a local variable or parameter?

查看:213
本文介绍了为什么是不好的做法,返回一个指针到一个局部变量或参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现我的学习指导这个问题,我不知道为什么它会是坏的指针返回一个局部变量/参数。任何想法?

I found this question on my study guide, and I am not sure why it would be bad to return a pointer to a local variable/parameter. Any ideas?

推荐答案

这与其说是一个不好的做法(这意味着它的可能的原因的问题)一样,因为它是一个惯例,将绝对会导致不确定的行为即可。这就像解引用一个空指针:不这样做,并期待您的程序逻辑的范围内行事。

It's not so much a "bad practice" (implying that it might cause problems) as much as it is a practice that will absolutely cause undefined behavior. It's like dereferencing a null pointer: don't do it and expect your program to behave within the limits of logic.

说明:

当一个局部变量(包括参数)被声明,它被赋予的自动存储的,这意味着,编译器花费的变量分配内存,然后解除分配内存,而不会对任何努力的护理程序员的一部分。

When a local variable (including a parameter) is declared, it is given automatic storage, meaning that the compiler takes care of allocating memory for the variable and then deallocating that memory without any effort on the part of the programmer.

void foo(int bar)
{
    int baz;
} //baz and bar dissappear here

当变量寿命结束(比如当函数返回时),编译器履行承诺,这是本地的函数的所有自动变量被破坏。这意味着任何指向这些变量立即指向该方案认为免费做任何它想要的垃圾内存。

When the variable' lifetime ends (such as when the function returns), the compiler fulfills its promise and all automatic variables that were local to the function are destroyed. This means that any pointers to those variables now point to garbage memory that the program considers "free" to do whatever it wants with.

当返回一个值,这不是问题:程序找到一个新的地方放值

When returning a value, this isn't a problem: the program finds a new place to put the value.

int foo(int bar)
{
    int baz = 6;
    return baz + bar; //baz + bar copied to new memory location outside of foo
} //baz and bar disapear

当您返回一个指针,指针的值被复制为正常。然而,指针仍然指向相同的位置也就是现在的垃圾

When you return a pointer, the value of pointer is copied as normal. However, the pointer still points to the same location which is now garbage:

int* foo(int bar)
{
    int baz = 6;
    baz += bar;
    return &baz; //(&baz) copied to new memory location outside of foo
} //baz and bar disapear! &baz is now garbage memory!

访问这个内存是不确定的行为,所以你的程序会以某种方式或其他几乎肯定胡作非为。例如,有一次我牺牲品这一确切的问题,虽然我的程序没有崩溃或终止,我的变量开始分解成垃圾值编译器重写自由的记忆。

Accessing this memory is undefined behavior, so your program will almost certainly misbehave in some way or other. For instance, I once fell victim to this exact problem, and while my program did not crash or terminate, my variables began degrading into garbage values as the compiler overwrote the "free" memory.

这篇关于为什么是不好的做法,返回一个指针到一个局部变量或参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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