简体   繁体   English

如果函数没有返回,调用堆栈是否会泄漏内存?

[英]Can the call stack leak memory if functions don't return?

I'm not sure how language specific this is, but in PHP in particular, can you leak memory in the call stack if some functions never return? 我不确定这是特定语言的,但特别是在PHP中,如果某些函数永远不会返回,你可以在调用堆栈中泄漏内存吗?

For example, suppose you have a long function with redirect() (or gotos in C) statement(s), how does the language or environment know to delete that frame of the stack? 例如,假设你有一个带有redirect()(或C语言中的gotos)语句的long函数,语言或环境如何知道删除堆栈的那个帧? Is there a method it uses to determine a stack frame will never be returned to? 是否有一个方法用于确定堆栈帧永远不会返回?

If your function does not return anything is some situations, then that sounds to me like a bad design issue. 如果你的功能在某些情况下没有返回任何东西,那么这对我来说就像一个糟糕的设计问题。 And no it should not cause any memory leak just by not returning anything. 并且不会因为没有返回任何内容而导致任何内存泄漏。

Whether the return value of your function ends up being used or not, you should either always have a path that return something (null, false, or any value). 无论函数的返回值是否最终被使用,您应该总是有一个返回某些东西的路径(null,false或任何值)。 Or you could never ever return anything ... in which case your function will be more like a method or a procedure as other programming languages would refer to it. 或者你永远不会返回任何东西......在这种情况下,你的函数将更像是一种方法或程序,就像其他编程语言所指的那样。

If you are having a memory leak in the function you are working with, than you need to scrutinize the code of the function to see what could be causing the leak. 如果您正在使用的函数中存在内存泄漏,则需要仔细检查函数的代码以查看可能导致泄漏的原因。

This question answered by Memory leak on the stack Note: I did come across that question before I posted this one but I didn't understand the answers until doing more research. 堆栈中内存泄漏回答了这个问题注意:在我发布这个问题之前我确实遇到过这个问题但是在做更多研究之前我不明白答案。

Tl;Dr: PHP maintains a stack for each page. Tl; Dr:PHP为每个页面维护一个堆栈。 In C/C++ "automatic duration" storage is cleaned up automatically by the compiler telling the operating system to delete automatic duration allocations when program execution moves outside the scope of those allocations. 在C / C ++中,“自动持续时间”存储由编译器自动清理,告诉操作系统在程序执行超出这些分配范围时删除自动持续时间分配。

So I guess the compiler can detect execution paths that result in the function not returning and also 'marks'(?) those paths as moving out of scope in the same way that returns are marked as moving out of scope. 所以我猜编译器可以检测导致函数不返回的执行路径,并且还将那些路径“标记”(?)移出范围,就像返回被标记为移出范围一样。

https://en.cppreference.com/w/cpp/language/storage_duration https://en.cppreference.com/w/cpp/language/storage_duration

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

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