gpt4 book ai didi

c++ - 指针电阻

转载 作者:太空狗 更新时间:2023-10-29 19:38:58 25 4
gpt4 key购买 nike

如果 *get_ii() 返回的是堆内存,而不是栈内存,这个问题会被消除吗?

01 int *get_ii()  
02 {
03 int ii; // Local stack variable
04 ii = 2;
05 return ⅈ
06 }
07 main()
08 {
09 int *ii;
10 ii = get_ii(); // After this call the stack is given up by the routine
11 // get_ii() and its values are no longer safe.
12
13 ... Do stuff
14 .. ii may be corrupt by this point.
15 }

来源 - http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html

谢谢

最佳答案

是的。从堆中分配可以在这里工作。确保在某处再次释放它,否则会泄漏内存。

智能指针通常有助于实现这种“不要忘记”逻辑。

关于c++ - 指针电阻,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3451799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com