Skip to content

Instantly share code, notes, and snippets.

@codedot
Created May 20, 2011 08:09
Embed
What would you like to do?
Stack Allocator Test
CFLAGS = -g
all: salloc
./salloc
clean:
-rm -fr salloc salloc.dSYM
#include <assert.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void hack(int siz, char **ptr, jmp_buf *jmp)
{
char buf[siz];
assert(ptr);
*ptr = buf;
assert(jmp);
longjmp(*jmp, 0);
}
void *salloc(int siz)
{
jmp_buf jmp;
char *ptr = NULL;
if (!setjmp(jmp))
hack(siz, &ptr, &jmp);
return ptr;
}
static void garbage(int n)
{
float x = n * n;
if (n)
garbage(--n);
}
int main(int argc, char *argv[])
{
char *buf = salloc(BUFSIZ);
if (!buf)
return 1;
strcpy(buf, "Hello World! And something else...");
garbage(BUFSIZ);
printf("%s\n", buf);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment