Created
January 14, 2013 18:49
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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