I'm kinda new to C programming and decided that making a brainfuck interpreter in C would be a good way to learn the language. I could write and tested with these bf codes:
this should print a hello world
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
this works as expected, so i thought my interpreter worked fine, but when I tested with a few variants of the hello world code, strange things happened.
this bf code should also print a hello world, but instead it prints out ²♣■■ÖFu ÖÖ■♦u
--<-<<+[+[<+>--->->->-<<<]>]<<--.<++++++.<<-..<<.<+.>>.>>.<<<.+++.>>.>>-.<<<+.
this bf code should also print a hello world, but instead the program gets stuck
+[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++[.>]<<<<.+++.------.<<-.>>>>+.
this is the code I wrote to interprete brainfuck:
#include <stdio.h>
int main(int argc, char const *argv[])
{
if (argc == 1)
{
printf("You must specify a file path\n");
return -1;
}
//amount of memory locations available
int mem = 30000;
//creating an integer array with mem positions
char arr[mem];
//current memory position
int index = 0;
//setting everything to 0
for (int i = 0; i < mem; i++)
{
arr[i] = 0;
}
FILE *file = fopen(argv[1], "r");
if (file == NULL)
{
printf("ERROR, file couldn't be read\n");
return -1;
}
//reading util the END OF THE FILE
char c;
while ((c = fgetc(file)) != EOF)
{
if (c == '+')
{
arr[index]++;
}
else if (c == '-')
{
arr[index]--;
}
else if (c == '>')
{
index++;
index %= mem;
}
else if (c == '<')
{
index--;
index %= mem;
}
else if (c == '.')
{
printf("%c", arr[index]);
}
else if (c == ',')
{
scanf("%c", &arr[index]);
}
else if (c == '[')
{
char temp = fgetc(file);
int skip = 0;
while (temp != ']' || skip != 0)
{
if (temp == '[')
skip++;
if (temp == ']' && skip > 0)
skip--;
temp = fgetc(file);
}
fseek(file, -1, SEEK_CUR);
}
else if (c == ']')
{
if (arr[index] != 0)
{
fseek(file, -2, SEEK_CUR);
char temp = fgetc(file);
int skip = 0;
while (temp != '[' || skip != 0)
{
if (temp == ']')
skip++;
if (temp == '[' && skip > 0)
skip--;
fseek(file, -2, SEEK_CUR);
temp = fgetc(file);
}
}
else
{
continue;
}
}
}
fclose(file);
return 0;
}
Thanks a lot if you can help me out on this one.
There's could be a problem with this piece of code, when index
become negative.
index--;
index %= mem;
%
operator retains the sign of the left argument, so -1 % mem
is –1, not mem–1 you may expect.