我可以将数据推送/弹出到 GCC C 返回堆栈吗?

标签 c gcc stack

在 GCC C 中,有没有办法将数据推送/弹出到 C 返回堆栈?

我不是在谈论实现我自己的堆栈(我知道该怎么做);我的意思是使用现有的 C 返回堆栈来显式压入/弹出参数(当然是在同一级别的大括号​​内)。

例如,像这样的东西:

extern int bar;

void foo(void) {
  PUSH(bar);

  bar = 12;
  doSomething(); // that depends on the value of bar

  bar = POP();   // restore original value of bar
}

如果有任何简单的方法可以做到这一点,我认为这将是一种比显式使用局部变量(如“oldBar”)更简洁的替代方法。

最佳答案

如果使用临时变量,基本上是一样的。临时变量分配在堆栈上或优化到寄存器。

例如

extern int bar;

void foo(void) {
  int tmp = bar
  bar = 12;
  doSomething(); // that depends on the value of bar
  bar = tmp;   // restore original value of bar
}

显然,C 实际上并不需要用于调用的堆栈结构,因此此功能没有意义。这是本文内存布局部分声明的https://www.seebs.net/c/c_tcn4e.html

Quite simply, not every compiler even has a "stack". Some systems don't really have any such feature. Every compiler for C has some kind of mechanism for handling function calls, but that doesn't mean it's a stack. More significantly, it is quite common for function parameters or local variables not to be stored on any "stack", but to be stored in CPU registers. That distinction can matter a lot, and should have been covered, rather than hand-waved away.

从技术上讲,您也可以使用 alloca()(位于 alloca.h 中)来执行此操作,但释放该内存的唯一方法是让函数调用返回。它也没有真正按照你的建议去做。 alloca 也不是 C 标准的一部分

关于我可以将数据推送/弹出到 GCC C 返回堆栈吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33701141/

相关文章:

c - 十六进制格式的IP地址范围搜索

c - 二叉树元素的递归 printf

c - 函数调用中的 static 关键字

c - 何时在扩展的 GCC 内联汇编中使用特定的操作数约束?

exception-handling - 异常帧与返回堆栈上的其他数据有何区别?

c - SCTP 多宿主未按预期工作

c - 当结构初始化与结构类型定义不匹配时,如何让 GCC 给出错误消息?

c - 为什么 malloc(sizeof(pointer)) 有效?

c++ - Stack 的链表实现

c++ - 结构化异常情况下的堆栈展开