当前位置: 首页 > 知识库问答 >
问题:

brainfuck中的嵌套循环

宇文卓
2023-03-14

我用C写了一个brainfuck解释器。这个程序有链表的实现,链表存储brainfuck指令,堆栈存储brainfuck的“[”指令。

我认为我的程序并不是在所有情况下都支持嵌套循环。这很荒谬,但这个brainfuck程序可以正确地使用我的Interpeter并打印“Hello World!”到stdout:

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

但该程序无法正常工作,并将内存错误打印到标准输出:

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

这两个例子适用于在线中断器-https://copy.sh/brainfuck/.

我试图解决这个问题,但我花了很多时间,但我失败了,所以我请求你帮助我。

这是我翻译的代码:

#include <stdio.h>
#include <sysexits.h>
#include <string.h>
#include <stdlib.h>

#define EX_SUCCESS 0

#define str1_is_less_than_str2 (strcmp("bf", file_extension) < 0)
#define str2_is_less_than_str1 (strcmp("bf", file_extension) > 0)

#define MEMSIZE 30000
#define NUMBER_OF_BF_INSTRUCTIONS 8

#define FIRST_ELEMENT_NOT_EXISTS (*head_ptr == NULL)

struct bf_instruction_node {
    int bf_instruction;
    struct bf_instruction_node *next_element;
};

struct stack_node {
    struct bf_instruction_node *bf_instr_ptr;
    struct stack_node *link;
};

void inc_ptr(int **values_ptr) { ++(*values_ptr); }
void dec_ptr(int **values_ptr) { --(*values_ptr); }
void inc_value(int *values_ptr) { ++(*values_ptr); }
void dec_value(int *values_ptr) { --(*values_ptr); }
void print_value(int *values_ptr) { putchar(*values_ptr); }
void input_value(int *values_ptr) { *values_ptr = getchar(); }

void push(struct stack_node **esp_ptr, struct bf_instruction_node *current_instr_ptr) {
    struct stack_node *new_element_on_the_stack;
    new_element_on_the_stack = (struct stack_node *)malloc(sizeof(struct stack_node));
    new_element_on_the_stack->bf_instr_ptr = current_instr_ptr;
    new_element_on_the_stack->link = *esp_ptr;
    *esp_ptr = new_element_on_the_stack;
}

void pop(struct stack_node **esp_ptr) {
    struct stack_node *tmp;
    tmp = *esp_ptr;
    *esp_ptr = (*esp_ptr)->link;
    free(tmp);
}

void start_loop(int *values_ptr, struct stack_node **esp_ptr, struct bf_instruction_node *current_instr_ptr) {
    push(esp_ptr, current_instr_ptr);
}

void end_loop(int *values_ptr, struct bf_instruction_node **current_instr_ptr, struct stack_node **esp_ptr) {
    if( *values_ptr != 0  ) {
        if( *values_ptr < 0 )
            *values_ptr = 255;
        if( *values_ptr > 255 )
            *values_ptr = 0;

        *current_instr_ptr = (*esp_ptr)->bf_instr_ptr;
        // *current_instr_ptr = (*current_instr_ptr)->next_element;
    } else  {
        pop(esp_ptr);
    }
}

void execute_instructions(int **values_ptr, struct bf_instruction_node *head_ptr, struct bf_instruction_node **current_instr_ptr) {
    struct stack_node *esp_ptr = NULL;

    char brainfuck_instruction;
    *current_instr_ptr = head_ptr;

    while( *current_instr_ptr != NULL ) {
        brainfuck_instruction = (*current_instr_ptr)->bf_instruction;

        switch( brainfuck_instruction ) {
            case '>': inc_ptr(values_ptr);                                  break;
            case '<': dec_ptr(values_ptr);                                  break;
            case '+': inc_value(*values_ptr);                               break;
            case '-': dec_value(*values_ptr);                               break;
            case '.': print_value(*values_ptr);                             break;
            case ',': input_value(*values_ptr);                             break;
            case '[': start_loop(*values_ptr, &esp_ptr, *current_instr_ptr);break;
            case ']': end_loop(*values_ptr, current_instr_ptr, &esp_ptr);   break;
        }

        *current_instr_ptr = (*current_instr_ptr)->next_element;
    }
}

struct bf_instruction_node *create_new_element(struct bf_instruction_node **head_ptr, struct bf_instruction_node **current_instr_ptr, int char_from_file) { 
    struct bf_instruction_node *new_element;
    *current_instr_ptr = *head_ptr;

    while( (*current_instr_ptr)->next_element != NULL )
        *current_instr_ptr = (*current_instr_ptr)->next_element;

    new_element = (struct bf_instruction_node *)malloc(sizeof(struct bf_instruction_node));

    return new_element;
}

void add_instruction_to_the_list(struct bf_instruction_node **head_ptr, struct bf_instruction_node **current_instr_ptr, int char_from_file) {
    if( FIRST_ELEMENT_NOT_EXISTS ) {
        *head_ptr = (struct bf_instruction_node *)malloc(sizeof(struct bf_instruction_node));

        if( *head_ptr == NULL ) {
            perror("Memory allocation failed");
            exit(EXIT_FAILURE);
        } else {
            (*head_ptr)->bf_instruction = char_from_file;
            (*head_ptr)->next_element = NULL;
            *current_instr_ptr = *head_ptr;
        }
    } else {
        struct bf_instruction_node *new_element = create_new_element(head_ptr, current_instr_ptr, char_from_file);

        if( new_element == NULL ) {
            perror("Memory allocation failed.");
            exit(EXIT_FAILURE);
        } else {
            new_element->bf_instruction = char_from_file;
            new_element->next_element = NULL;
            (*current_instr_ptr)->next_element = new_element;
            *current_instr_ptr = new_element;
        }
    }
}

void print_instructions(struct bf_instruction_node *head_ptr, struct bf_instruction_node **current_instr_ptr) {
    *current_instr_ptr = head_ptr;

    while( *current_instr_ptr != NULL ) {
        printf("%c", (*current_instr_ptr)->bf_instruction);
        *current_instr_ptr = (*current_instr_ptr)->next_element;
    }
}

void clear_the_memory(struct bf_instruction_node *head_ptr, struct bf_instruction_node **current_instr_ptr) {
    struct bf_instruction_node *earlier_element;

    *current_instr_ptr = head_ptr;

    while( (*current_instr_ptr) != NULL ) {
        earlier_element = *current_instr_ptr;
        *current_instr_ptr = (*current_instr_ptr)->next_element;
        free(earlier_element);
    }

    puts("Memory is cleared.");
}

const char *is_bf_instruction(int char_from_file) {
    const char bf_alphabet[NUMBER_OF_BF_INSTRUCTIONS] = {'>', '<', '+', '-', ',', '.', '[', ']'};
    return memchr(bf_alphabet, char_from_file, sizeof(bf_alphabet));
}

const char *get_file_extension(const char *filename) {
    const char *dot = strchr(filename, '.');

    if( dot == NULL )
        return NULL;

    const char *file_extension = dot + 1;
    return file_extension;
}

int main(int argc, char **argv) {
    if( argc < 2 ) {
        fprintf(stderr, "File not specified.\n");
        puts("usage: ./bf_interpreter <filename.bf>");
        return EX_USAGE;
    }

    const char *filename = argv[1];
    const char *file_extension = get_file_extension(filename);

    if( file_extension == NULL || str1_is_less_than_str2 || str2_is_less_than_str1 ) {
        fprintf(stderr, "Incorrect file extension.\n");
        puts("usage: ./bf_interpreter <filename.bf>");
        return EX_DATAERR;
    }

    FILE *file_with_bf_code = fopen(filename, "r");

    if( file_with_bf_code == NULL ) {
        perror(filename);
        return EX_NOINPUT;
    }

    int values[MEMSIZE] = {0}, *values_ptr = values;
    int char_from_file;

    struct bf_instruction_node *head_ptr = NULL, *current_instr_ptr;

    while( (char_from_file = fgetc(file_with_bf_code)) != EOF ) {
        if( is_bf_instruction(char_from_file) != NULL )
            add_instruction_to_the_list(&head_ptr, &current_instr_ptr, char_from_file);
    }

    execute_instructions(&values_ptr, head_ptr, &current_instr_ptr);
    clear_the_memory(head_ptr, &current_instr_ptr);

    return EX_SUCCESS;
}

我认为这个函数会产生内存冲突的错误:

void end_loop(int *values_ptr, struct bf_instruction_node **current_instr_ptr, struct stack_node **esp_ptr) {
    if( *values_ptr != 0  ) {
        if( *values_ptr < 0 )
            *values_ptr = 255;
        if( *values_ptr > 255 )
            *values_ptr = 0;

        *current_instr_ptr = (*esp_ptr)->bf_instr_ptr;
        // *current_instr_ptr = (*current_instr_ptr)->next_element;
    } else {
        pop(esp_ptr);
    }
}

我希望有人能帮我。干杯并提前感谢你们!

共有2个答案

劳昊明
2023-03-14

无论如何(如果这个问题仍然相关)-我认为问题是您没有正确实现start_loop。在循环的开始('['char)-如果当前位置的内容为0-循环将被完全跳过。

在您的代码中——您只需继续执行代码,而不考虑当前单元格内容,这是一个错误。

此外,我不确定您的循环结束实现是否正确。在循环检查期间,不需要篡改单元格内容。只需检查一下内容。零出口循环。非零-返回到相应的循环开始。

史钊
2023-03-14

你需要调试。

我试过你的密码。根据我是否使用优化,得到了不同的结果。这是未定义行为的良好迹象。通过优化-O3-O2我得到了这个错误:

Program received signal SIGSEGV, Segmentation fault.
execute_instructions (values_ptr=0x7ffffffe0ca8, head_ptr=<optimized out>, current_instr_ptr=0x7ffffffe0cb8) at bf.c:83
83              case ']': end_loop(*values_ptr, current_instr_ptr, &esp_ptr);   break;

使用-O1给出:

$ ./a.out fil.bf 
��Memory is cleared.

没有优化只是似乎陷入了一个无休止的循环中。我让它运行了大约5秒钟,但什么也没发生。

此外,您的代码会产生两个警告:

$ gcc -Wall -Wextra -std=c11 -pedantic bf.c
bf.c: In function ‘start_loop’:
bf.c:48:22: warning: unused parameter ‘values_ptr’ [-Wunused-parameter]
 void start_loop(int *values_ptr, struct stack_node **esp_ptr, struct bf_instruction_node *current_instr_ptr) {
                      ^~~~~~~~~~
bf.c: In function ‘create_new_element’:
bf.c:90:139: warning: unused parameter ‘char_from_file’ [-Wunused-parameter]
 struct bf_instruction_node *create_new_element(struct bf_instruction_node **head_ptr, struct bf_instruction_node **current_instr_ptr, int char_from_file) {
                                                                                                                                           ^~~~~~~~~~~~~~
 类似资料:
  • 问题内容: 我需要在Robot框架中创建一个嵌套循环。你能帮我吗? 我需要一个嵌套循环,将所有循环与文件中的所有循环进行比较。 提前致谢 问题答案: RF中没有嵌套循环;这只能通过在外部的内部循环调用一个关键字来完成。 不过,在您的特定情况下,可以不使用它-因为您想匹配整行,所以可以通过“应包含”来实现: 如果您要进行部分比赛-即成为会员的一部分,那么就不可能这样。

  • 我有一个这样的数组 我想做的是前面的模型,为其数量绘制徽标,因此三星=3,索尼=7,以此类推,将绘制3个索尼徽标和7个三星徽标。 我想出了这样的办法 但是当然,所有这些都是为了每个数组条目,呼应出名称,所以我最终打印了5个三星,打印了5个索尼,等等。 如何使其使用 qty 数组的值而不是条目数?

  • 我用For创建了一个嵌套循环,这是程序代码和输出,然后我尝试了同时循环,得到了不同的结果 对于 虽然 请引导我。。谢谢

  • Python 不仅支持 if 语句相互嵌套,while 和 for 循环结构也支持嵌套。所谓嵌套(Nest),就是一条语句里面还有另一条语句,例如 for 里面还有 for,while 里面还有 while,甚至 while 中有 for 或者 for 中有 while 也都是允许的。 当 2 个(甚至多个)循环结构相互嵌套时,位于外层的循环结构常简称为 外层循环或 外循环,位于内层的循环结构常简

  • 这是我的代码。我遇到的问题是,我希望将HP在我的PHP代码中的数字转换为我的HP HTML代码,以及与Cylinder相同的内容。我已经想好了其他的东西,但说到这一部分我就卡住了

  • 本文向大家介绍MATLAB嵌套循环,包括了MATLAB嵌套循环的使用技巧和注意事项,需要的朋友参考一下 示例 可以嵌套循环,以在另一个迭代任务中执行迭代任务。考虑以下循环: 我们使用2个迭代器来显示abc和中元素的所有组合1:m,从而得出: 我们还可以使用嵌套循环来组合每次要完成的任务和几次迭代中要完成的任务: 这里我们要计算所有的斐波那契数列,但是n每次只显示第一个元素,所以我们得到 我们可以做