Skip to content

Instantly share code, notes, and snippets.

@eatnumber1
Created January 14, 2013 18:49
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eatnumber1/4532314 to your computer and use it in GitHub Desktop.
Save eatnumber1/4532314 to your computer and use it in GitHub Desktop.
A awesome^H^H^H^H^H^H^Hdisgusting use of the stack in C.
#include <stdio.h>
#include <setjmp.h>
#include <stddef.h>
#include <string.h>
#define NORETURN __attribute__((noreturn))
typedef void (*AllocCont)( void * );
void NORETURN longjmp_on_return( AllocCont f, jmp_buf env, void *mem ) {
f(mem);
longjmp(env, 1);
}
void NORETURN alloc_and_call( AllocCont f, size_t size, jmp_buf env, char *parent_ptr ) {
char ptr;
if( parent_ptr == NULL || parent_ptr - &ptr < (ptrdiff_t) size ) {
alloc_and_call(f, size, env, parent_ptr == NULL ? &ptr : parent_ptr);
} else {
longjmp_on_return(f, env, &ptr);
}
}
void sls_alloc( size_t size, AllocCont f ) {
jmp_buf env;
if( setjmp(env) == 0 )
alloc_and_call(f, size, env, NULL);
}
const char *message = "Hello World!";
void do_stuff( char *mem ) {
strcpy(mem, message);
printf("%s\n", mem);
}
int main() {
sls_alloc(strlen(message) + 1, (AllocCont) do_stuff);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment