gpt4 book ai didi

c - 使用 GOTO 时 StackFrames 会受到怎样的影响?

转载 作者:太空宇宙 更新时间:2023-11-04 01:20:37 26 4
gpt4 key购买 nike

我正在关注 Memory Layout And The Stack理解栈帧..

作者很好地解释了堆栈帧并说明了在给定时间点堆栈中的内容

他还在下面问了一些问题

  • 假设一个程序进行了 5 次函数调用。堆栈上应该有多少帧?
  • 我们看到堆栈向下线性增长,并且当函数返回时,堆栈上的最后一帧被释放并返回到未使用的内存。是否有可能将堆栈中间某处的帧返回到未使用的内存?如果是这样,那对正在运行的程序意味着什么?
  • goto() 语句能否导致堆栈中间的帧被释放?答案是否定的,但为什么呢?
  • longjmp() 能否导致堆栈中间的帧被释放?

下面是我尝试回答上述问题

  • Suppose a program makes 5 function calls. How many frames should be on the stack?

如果函数相互独立,则只有主函数或主函数和调用函数在栈中

We saw that the stack grows linearly downward, and that when a function returns, the last frame on the stack is deallocated and returned to unused memory. Is it possible for a frame somewhere in the middle of the stack to be returned to unused memory? If it did, what would that mean about the running program?

我认为这是不可能的,因为这可能会破坏内存

我不确定其余的问题。你能帮忙解决这个问题吗

如果您需要更多信息,请告诉我

最佳答案

Suppose a program makes 5 function calls. How many frames should be on the stack?

最多6个(假设在调用所有函数之前没有函数返回)。一个用于 main(),一个用于每个函数调用。

We saw that the stack grows linearly downward, and that when a function returns, the last frame on the stack is deallocated and returned to unused memory. Is it possible for a frame somewhere in the middle of the stack to be returned to unused memory? If it did, what would that mean about the running program?

不,因为堆栈是 不允许随机访问删除。您只能从堆栈中弹出。

Can a goto() statement cause frames in the middle of the stack to be deallocated? The answer is no, but why?

因为它会改变堆栈展开。使用 goto 退出代码块不会展开堆栈,这是您应该(几乎)永远不要使用 goto 的原因之一。在 What is stack unwinding? 中阅读更多内容但是,请注意,这是与 C++ 相关的,在 C 中,goto out of block 是明确定义的,正如 Antti 所提到的。

Can longjmp() cause frames in the middle of the stack to be deallocated?

我想是的,因为这是一个特殊的案例。但这与我的第二个答案有点矛盾。

当通过 setjmp/longjmp 执行“非本地转到”时,不会发生正常的“堆栈展开”。因此,也不会发生任何必需的清理操作。

来自 C 的 longjmp() 函数(有关 setjmp.h 的基础知识,请参阅 Wikipedia entry)。 longjmp() 跳下堆栈 到相应的 setjmp(),跨越与它们之间的堆栈帧一样多的堆栈帧。与我们将看到的其他方法不同,longjmp() 不会遍历帧列表,它只是一次性地遍历所有帧,肆意无视它们可能包含的任何珍贵或美丽的东西。

阅读更多相关信息 here .

longjmp() 会将堆栈返回到之前使用 setjmp() 保存的状态。如果中间的任何框架被移除,那么下面的所有框架也被移除;即,如 Klas 所述,在 longjmp 之后堆栈中不会有“漏洞”。

关于c - 使用 GOTO 时 StackFrames 会受到怎样的影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43998087/

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