【问题标题】:Avoiding stack overflow using a trampoline使用蹦床避免堆栈溢出
【发布时间】:2020-04-15 22:38:25
【问题描述】:

下面程序中的蹦床功能正常工作。我认为下面的程序会导致堆栈溢出,因为函数 thunk_f 和 thunk1 无限期地相互调用,从而导致创建新的堆栈帧。但是,我想编写一个行为更类似于非终止循环的程序,因为蹦床应该防止堆栈溢出。

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

void trampoline(void *(*func)()) {
  while (func) {
    void *call = func();
    func = (void *(*)())call;
  }
}

void *thunk1(int *param);
void *thunk_f(int *param);

void *thunk1(int *param)
{
  ++*param;
  trampoline(thunk_f(param));
  return NULL;
}

void *thunk_f(int *param) 
{
  return thunk1(param);
}

int main(int argc, char **argv)
{
  int a = 4;
  trampoline(thunk1(&a));
  printf("%d\n", a);
}

【问题讨论】:

  • trampoline的定义在哪里?
  • thunk1 似乎调用了thunk_f,它调用了thunk1,它调用了thunk_f,它......
  • 好吧,不这样做可以避免堆栈溢出。
  • 据我所知,没有合法的非终止循环用例。每个有用的循环实例最终都会终止。
  • @PaulHankin 该技术已经成熟。在这里只是误用了。

标签: c trampolines


【解决方案1】:

您错误地使用了蹦床:与其让它调用您的thunk_f 函数,不如使用thunk_f 函数的result 调用它。

因此,您会遇到堆栈溢出。您可以通过 返回 thunk_f 而不是调用它来避免堆栈溢出(但不是无限循环):

void *thunk1(int *param)
{
  ++*param;
  return thunk_f;
}

并在main 中正确调用trampoline

int main(int argc, char **argv)
{
  int a = 4;
  trampoline(thunk1, &a);
  printf("%d\n", a);
}

当然,这需要trampoline 获得一个额外的参数,以传递&amp;a 参数:

void trampoline(void *(*func)(int *), int *arg) {
  while (func) {
    void *call = func(arg);
    func = (void *(*)())call;
  }
}

这行得通——但如前所述,它只是一个没有输出的无限循环。要查看发生了什么,请将printf 放入thunk1

void *thunk1(int *param)
{
  printf("%d\n", ++*param);
  return thunk_f;
}

最后,我应该注意到这是无效的 C,因为在对象指针和函数指针之间进行转换是非法的(编译时总是带有迂腐警告!)。为了使代码合法,请将函数指针包装到一个对象中:

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

struct f {
    struct f (*p)(void *);
};

void trampoline(struct f f, void *args) {
    while (f.p) {
        f = (f.p)(args);
    }
}

struct f thunk1(void *param);
struct f thunk_f(void *param);

struct f thunk1(void *param) {
    printf("%d\n", ++*((int *) param));
    return (struct f) {thunk_f};
}

struct f thunk_f(void *param) {
    return thunk1(param);
}

int main() {
    int a = 4;
    trampoline((struct f) {thunk1}, &a);
}

【讨论】:

  • 当然thunk_f 也可以通过用return (struct f) {thunk1}; 替换正文来执行延续传递而不是显式调用thunk1
猜你喜欢
  • 2018-11-02
  • 2020-10-03
  • 2016-07-12
  • 2016-03-24
  • 2020-03-08
  • 2010-11-30
  • 1970-01-01
  • 2011-09-21
  • 2015-11-14
相关资源
最近更新 更多