Skip to content

Instantly share code, notes, and snippets.

@maxcountryman
Created February 1, 2012 01:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxcountryman/1714336 to your computer and use it in GitHub Desktop.
Save maxcountryman/1714336 to your computer and use it in GitHub Desktop.
A brainfuck interpreter in C with dynamic memory allocation
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* add_cell(char* tape, size_t *tape_size) {
char* tmp = (char*)realloc(tape, (++*tape_size) * sizeof(char));
if (tmp == NULL) {
printf("FATAL: Could not reallocate tape memory!");
exit(1);
}
if (!tape[*tape_size-1]) {
tape[*tape_size-1] = 0;
}
return tmp;
}
char* remove_cell(char* tape, size_t *tape_size, char* ptr) {
char tail = tape[*tape_size-1];
// if the cell is zeroed and not pointed to currently
if (tail == 0 && ptr != &tape[*tape_size-1] && *tape_size > 0) {
char* tmp = (char*)realloc(tape, (--*tape_size) * sizeof(char));
if (tmp == NULL) {
printf("FATAL: Could not reallocate tape memory!");
exit(1);
}
return tmp;
}
return tape;
}
void interpret(char* input) {
size_t tape_size = 1;
char* tape;
char* ptr;
char current_char;
size_t i;
size_t loop;
tape = (char*)calloc(tape_size, sizeof(char));
ptr = tape;
for (i = 0; input[i] != 0; i++) {
current_char = input[i];
if (current_char == '>') {
tape = add_cell(tape, &tape_size);
++ptr;
} else if (current_char == '<') {
--ptr;
} else if (current_char == '+') {
++*ptr;
} else if (current_char == '-') {
--*ptr;
} else if (current_char == '.' ) {
putchar(*ptr);
} else if (current_char == ',') {
*ptr = getchar();
} else if (current_char == ']' && *ptr) {
loop = 1;
while (loop > 0) {
current_char = input[--i];
if (current_char == '[') {
loop--;
} else if (current_char == ']') {
loop++;
}
}
}
// garbage collect
tape = remove_cell(tape, &tape_size, ptr);
}
free(tape);
}
int main() {
interpret(",[.[-],]"); // outputs input
return 0;
}
@nickdesaulniers
Copy link

Missing the '[' case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment