Skip to content

Commit

Permalink
Add support for negative difference values
Browse files Browse the repository at this point in the history
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
  • Loading branch information
fabianishere committed Nov 5, 2021
1 parent b131824 commit 5941523
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/brainfuck.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down

0 comments on commit 5941523

Please sign in to comment.