整数指针与 char 指针的悬垂指针

Dangling pointer in case of integer pointer vs char pointers

我想了解悬空指针在 C++ 中的工作原理。

int* get_int_ptr()
{
    int i=10;
    int* ptr;
    ptr = &i;
    return ptr;
}

char* get_char_ptr()
{
    char str[10];
    strcpy(str,"Hello!");
    return(str); 
}

int main()
{
    cout << *get_int_ptr() << endl;
    cout << get_char_ptr() << endl;
    return 0;
}

这段代码的输出是-

警告:

prog.cpp: In function 'char* get_char_ptr()':
prog.cpp:16:9: warning: address of local variable 'str' returned [-Wreturn-local-addr]
char str[10];
    ^

输出:

10

有人可以解释为什么 i 的值打印在 main() 函数中,即使返回的指针指向 i 已经超出范围。

以及为什么 str 的值没有打印出来。

int*char*在功能范围上是分开对待的

此外,在这里使用 smart_pointers 是否有任何帮助?

打印出来的东西是偶然的。

两个指针都指向函数returns时停止存在的局部变量。

这是未定义行为的经典示例。

任何事情都有可能发生 - 程序可能会为你订披萨、爆炸或打印一些东西 - 有时甚至是正确的值。

如您所知,返回一个指向局部变量的指针并不能保证有效。因此,您的 get_int_ptrget_char_ptr 函数都不能正常工作。

(埋下答案:"not guaranteed to work"和"guaranteed not to work"不太一样。)

您试验了 get_int_ptr 函数。令您惊讶的是,调用程序 "correctly" 打印出 10.

打个比方。你所做的就像这个小故事:

I was working on my car. I removed the front wheel to repair the brakes. When I put the front wheel back on, I forgot to install the lug nuts, so the wheel wasn't really attached. Then I drove to the store to buy some milk. But the wheel did not fall off. Why not?

答案是,你非常非常幸运。

然后您试验了 get_char_ptr 函数。它失败了。这不足为奇,除非您认为 get_int_ptr 实验的成功以某种方式证明悬挂指针毕竟可以使用。继续类比:

The next day, with the lug nuts still missing, I drove cross-country to visit my aging grandmother. Halfway there, while traveling at 60 mph on the highway, the front wheel suddenly flew off, and I crashed into the ditch, demolishing my car. Why did this happen?

不用说,是因为螺母不见了!前轮没有任何支撑,你显然 "success" 前一天,在那种破烂的情况下开车去商店,证明什么都没有。

我同意您的一个函数 "worked" 而另一个函数没有,这很有趣。但这基本上是随机事件。不,int*char* 指针在这方面没有区别:如果悬空,它们都同样可能不起作用。

有时可以解释为什么随机事件会以这种方式发生。但是,在这里,我不能。我已经在我的编译器下试过你的程序,我看到了完全相同的结果。 get_int_ptr 的局部变量 i 往往会保留下来,但 get_char_ptr 的局部数组 str 往往会被清除。我希望 str 的位可能会存活下来,但显然不会。但是,同样,我们无法解释该行为并不重要,因为它是 undefined.