Skip to content

Instantly share code, notes, and snippets.

@LeKSuS-04
Last active July 8, 2022 20:59
Show Gist options
  • Save LeKSuS-04/1fc3813a888526c48ffaa6061f5d5f88 to your computer and use it in GitHub Desktop.
Save LeKSuS-04/1fc3813a888526c48ffaa6061f5d5f88 to your computer and use it in GitHub Desktop.
Brainfuck interpreter in C
#include <stdio.h>
#include <stdlib.h>
const int MEMSIZE = 30000;
void run_bf(FILE *fptr) {
char cmd;
int mempos = 0, filepos = -1;
u_char *memory = calloc(MEMSIZE, sizeof(unsigned char));
int *jump_stack = calloc(MEMSIZE, sizeof(int));
int skip_cycle = 0;
if (!memory || !jump_stack) {
printf("Failed to allocate memory\n");
exit(1);
}
while (++filepos, (cmd = fgetc(fptr)) != EOF) {
if (skip_cycle) switch(cmd) {
case '[':
++skip_cycle;
break;
case ']':
--skip_cycle;
break;
default:
break;
}
else switch (cmd) {
case '>':
mempos = (mempos + 1) % MEMSIZE;
break;
case '<':
mempos = (mempos - 1 + MEMSIZE) % MEMSIZE;
break;
case '+':
++memory[mempos];
break;
case '-':
--memory[mempos];
break;
case '.':
printf("%c", memory[mempos]);
break;
case ',':
memory[mempos] = fgetc(stdin);
break;
case '[':
if (memory[mempos]) *jump_stack++ = filepos;
else ++skip_cycle;
break;
case ']':
--jump_stack;
if (memory[mempos]) {
filepos = *jump_stack - 1;
fseek(fptr, filepos + 1, SEEK_SET);
}
break;
default:
break;
}
}
free(memory);
free(jump_stack);
}
int main(int argc, char **argv) {
if (argc == 1) {
printf("Usage: bf <file.bf>\n");
exit(1);
}
FILE *fptr = fopen(argv[1], "r");
if (fptr == NULL) {
printf("Can't access file %s\n", argv[1]);
exit(1);
}
run_bf(fptr);
fclose(fptr);
return 0;
}
>++++++++++>+>+[
[+++++[>++++++++<-]>.<++++++[>--------<-]+<<<]>.>>[
[-]<[>+<-]>>[<<+>+>-]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-
[>+<-[>+<-[>+<-[>[-]>+>+<<<-[>+<-]]]]]]]]]]]+>>>
]<<<
]
This program doesn't terminate; you will have to kill it.
Daniel B Cristofani (cristofdathevanetdotcom)
http://www.hevanet.com/cristofd/brainfuck/
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++
.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.
------.--------.>+.>.
[squares2.b -- compute square numbers
(c) 2016 Daniel B. Cristofani
http://brainfuck.org/]
>>>>>>>>>>+>++<[
[[<<+>+>-]++++++[<++++++++>-]<-.[-]<<<]
++++++++++.[-]>>>>>[>>>>]<<<<[[<<<+>+>>-]<<<-<]>>++[
[
<<<++++++++++[>>>[->>+<]>[<]<<<<-]
>>>[>>[-]>>+<<<<[>>+<<-]]>>>>
]<<-[+>>>>]+[<<<<]>
]>>>[>>>>]<<<<-<<+<<
]
This program outputs square numbers. It doesn't terminate.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment