Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

nickdesaulniers commented Apr 26, 2013

Missing the '[' case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.