Skip to content

Instantly share code, notes, and snippets.

@minitech
Created October 26, 2015 00:13
Show Gist options
  • Save minitech/afd33b12caa0eb278d3f to your computer and use it in GitHub Desktop.
Save minitech/afd33b12caa0eb278d3f to your computer and use it in GitHub Desktop.
convenient & saf
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
// most code is single-threaded
unsigned char* current_mem;
void* readA();
void* readB();
void* auto_alloc(size_t size) {
unsigned char* result = current_mem;
current_mem += size;
return (void*)result;
}
void* automanage(void* (*f)(void)) {
// pretty much all the memory you'll ever need
unsigned char mem[5000];
unsigned char* prev_mem = current_mem;
current_mem = mem;
void* result = f();
current_mem = prev_mem;
return result;
}
int main(int argc, char* argv[]) {
puts("Enter two lines");
automanage(readA);
return EXIT_SUCCESS; // darn right
}
void* readA() {
char* input = auto_alloc(80);
gets(input); // no segmentation faults if you go past 80 - p. cool
automanage(readB);
printf("readA got: %s\n", input);
return NULL;
}
void* readB() {
char* input = auto_alloc(80);
gets(input);
printf("readB got: %s\n", input);
return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment