0

The trampoline function in the program below works properly. I think the program below results in stack overflow because the functions thunk_f and thunk1 call each other indefinitely, resulting in the creation of new stack frames. However, I want to write a program that behaves more similarly to a nonterminating loop, as trampolines should prevent stack overflow.

#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);
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501

1 Answers1

3

You are using the trampoline incorrectly: rather than letting it invoke your thunk_f function, you call it with the result of the thunk_f function.

As a result, you are getting a stack overflow. You can avoid the stack overflow (but not the infinite loop) by returning thunk_f instead of calling it:

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

And calling trampoline in main correctly:

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

And of course this requires that trampoline gets an additional argument, to pass the &a parameter on:

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

This works — but as noted, it’s just an infinite loop without output. To see what’s happening, put the printf inside thunk1:

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

Lastly, I should probably note that this is invalid C, because it’s illegal to convert between a object pointer and a function pointer (always compile with pedantic warnings!). To make the code legal, wrap the function pointer into an object:

#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);
}
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    And of course `thunk_f` could also perform continuation-passing instead of calling `thunk1` explicitly, by replacing the body with `return (struct f) {thunk1};`. – Konrad Rudolph Apr 15 '20 at 14:22