Skip to content

Instantly share code, notes, and snippets.

@msg555
Last active September 10, 2024 12:44
Show Gist options
  • Save msg555/5418199 to your computer and use it in GitHub Desktop.
Save msg555/5418199 to your computer and use it in GitHub Desktop.
Stack Switching
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE (1 << 26)
#define STACK_PAD 128
int rec(int n) {
return n == 0 ? 0 : rec(n - 1) + 1;
}
int main() {
/* Allocate a new stack to use first. Because stacks grow to lower addresses
* we want to use just a little before the end of the allocation. */
char* nstack = (char*)malloc(STACK_SIZE) + STACK_SIZE - STACK_PAD;
/* Adjust the stack pointer to fall right in our newly allocated stack.
* "char stack_hack[sz];" has the effect of subtracting sz from the stack
* pointer. */
char stack_hack[(char*)&nstack - nstack];
/* Now we can recurse deeply. If you comment out the definition of stack_hack
* then (on my system's limits, anyway) the second one will segfault. */
printf("%d\n", rec(100000));
printf("%d\n", rec(1000000));
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment