Brainfuck 解释器不是 运行 一些代码

Brainfuck interpreter not running some codes

我是 C 编程的新手,我决定用 C 语言制作一个 brainfuck 解释器是学习这门语言的好方法。我可以用这些 bf 代码编写和测试:

这应该打印一个 hello world

++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.

这按预期工作,所以我认为我的解释器工作正常,但是当我测试 hello world 代码的几个变体时,奇怪的事情发生了。

这段 bf 代码也应该打印一个 hello world,但它却打印出了 ²♣■■ÖFu ÖÖ■♦u

--<-<<+[+[<+>--->->->-<<<]>]<<--.<++++++.<<-..<<.<+.>>.>>.<<<.+++.>>.>>-.<<<+.

这个 bf 代码也应该打印一个 hello world,但是程序卡住了

+[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++[.>]<<<<.+++.------.<<-.>>>>+.

这是我为解释 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;
}

非常感谢你能帮我解决这个问题。

index 变为负数时,这段代码可能有问题。

        index--;
        index %= mem;

% 运算符保留左参数的符号,因此 -1 % mem 是 –1,而不是您可能期望的 mem–1。