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

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

问题描述

我在我的学习指南上发现了这个问题,我不确定为什么返回指向局部变量/参数的指针会很糟糕.有什么想法吗?

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 variables' 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 another. 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天全站免登陆