From 4e62be46f7dbcbf425c06998055d39d05506d433 Mon Sep 17 00:00:00 2001 From: id101010 Date: Wed, 9 Nov 2016 00:15:40 +0100 Subject: [PATCH] Fixed bug for nested loops. --- Makefile | 2 +- bfckr.c | 24 +++++++++++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 92eeaa6..f7fa246 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ HFILES=$(shell find . -name '*.h') STYLE=astyle --style=1tbs RUN=valgrind --leak-check=full DEBUG=gdb --args -ARGS="examples/hello.bf" +ARGS="examples/rot13.bf" all: build run diff --git a/bfckr.c b/bfckr.c index caaaa07..298aa4b 100644 --- a/bfckr.c +++ b/bfckr.c @@ -39,6 +39,8 @@ void die(const char *message) // Parses and executes a brainfuck expression void bfuck_parser(char *input) { + int loop = 0; + for(size_t i = 0; input[i] != 0; i++) { // where i is the instruction pointer switch(input[i]) { case '>': @@ -68,8 +70,16 @@ void bfuck_parser(char *input) case '[': if(*p == 0) { // if the byte at the data pointer is zero // jump forward to the command after the next ] - while(input[i] != ']') { + loop = 1; + // jump back to the command after the matching [ + while(loop > 0) { i++; + if(input[i] == '[') { + loop++; + } + if(input[i] == ']') { + loop--; + } } } else { continue; // increment instruction pointer @@ -78,10 +88,18 @@ void bfuck_parser(char *input) case ']': if(*p != 0) { // if the byte at the data pointer is nonzero - // jump back to the command after the previous [ - while(input[i] != '[') { + loop = 1; + // jump back to the command after the matching [ + while(loop > 0) { i--; + if(input[i] == '[') { + loop--; + } + if(input[i] == ']') { + loop++; + } } + } else { continue; // increment instruction pointer }