From 59415237188ff94ec7b0d8ebb32420aab4309c11 Mon Sep 17 00:00:00 2001 From: Fabian Mastenbroek Date: Fri, 5 Nov 2021 09:47:32 +0100 Subject: [PATCH] Add support for negative difference values This change fixes an issue with the tape overflow checking code, where it would incorrectly report that the tape was overrun/underrun when an instruction has a negative difference. This was caused by a cast to an unsigned long. Fixes #77 --- src/brainfuck.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/brainfuck.c b/src/brainfuck.c index 2664c97..c62c11f 100644 --- a/src/brainfuck.c +++ b/src/brainfuck.c @@ -482,16 +482,16 @@ void brainfuck_execute(BrainfuckInstruction *root, BrainfuckExecutionContext *co context->tape[context->tape_index] -= instruction->difference; break; case BRAINFUCK_TOKEN_NEXT: - if ((unsigned long) instruction->difference >= INT_MAX - context->tape_size || - (unsigned long) context->tape_index + instruction->difference >= context->tape_size) { + if (instruction->difference >= INT_MAX - (long) context->tape_size || + (long) context->tape_index + instruction->difference >= (long) context->tape_size) { fprintf(stderr, "error: tape memory out of bounds (overrun)\nexceeded the tape size of %zd cells\n", context->tape_size); exit(EXIT_FAILURE); } context->tape_index += instruction->difference; break; case BRAINFUCK_TOKEN_PREVIOUS: - if ((unsigned long) instruction->difference >= INT_MAX - context->tape_size || - context->tape_index - instruction->difference < 0) { + if (instruction->difference >= INT_MAX - (long) context->tape_size || + (long) context->tape_index - instruction->difference < 0) { fprintf(stderr, "error: tape memory out of bounds (underrun)\nundershot the tape size of %zd cells\n", context->tape_size); exit(EXIT_FAILURE); }