Created
October 26, 2015 00:13
-
-
Save minitech/afd33b12caa0eb278d3f to your computer and use it in GitHub Desktop.
convenient & saf
This file contains hidden or 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 <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