Skip to content

Instantly share code, notes, and snippets.

@codedot
Created May 20, 2011 08:09
Show Gist options
  • Save codedot/982535 to your computer and use it in GitHub Desktop.
Save codedot/982535 to your computer and use it in GitHub Desktop.
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