Skip to content

Commit 3f4ce15

Browse files
author
Chris Frank
committed
Don't run programs with unbalanced brackets
1 parent 7357f9e commit 3f4ce15

File tree

4 files changed

+26
-8
lines changed

4 files changed

+26
-8
lines changed

examples/unbalanced_close.bf

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
[[][][][[][][][[][][][][]]]]]

examples/unbalanced_open.bf

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
[[][][][[][][[][][]]]

src/brainfuck.c

+21-7
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
static const uint32_t TAPE_SIZE = 0x7530;
88

99
static cfbf_token cfbf_tokenize(char input);
10-
static void cfbf_generate_jumps(cfbf_state *state);
10+
static int cfbf_generate_jumps(cfbf_state *state);
1111

1212
extern cfbf_state *cfbf_initialize_state(FILE *file, int32_t size)
1313
{
@@ -67,7 +67,7 @@ extern cfbf_state *cfbf_initialize_state(FILE *file, int32_t size)
6767
return state;
6868
}
6969

70-
static void cfbf_generate_jumps(cfbf_state *state)
70+
static int cfbf_generate_jumps(cfbf_state *state)
7171
{
7272
cfbf_stack *stack = cfbf_create_stack();
7373

@@ -76,20 +76,34 @@ static void cfbf_generate_jumps(cfbf_state *state)
7676
cfbf_stack_push(stack, (uint32_t)i);
7777
} else if (state->commands[i].token == JMP_BACK) {
7878
uint32_t jmp_fwrd;
79-
cfbf_stack_pop(stack, &jmp_fwrd);
80-
81-
state->commands[jmp_fwrd].jmp_ptr = (int32_t)i;
82-
state->commands[i].jmp_ptr = (int32_t)jmp_fwrd;
79+
if (cfbf_stack_pop(stack, &jmp_fwrd)) {
80+
state->commands[jmp_fwrd].jmp_ptr = (int32_t)i;
81+
state->commands[i].jmp_ptr = (int32_t)jmp_fwrd;
82+
} else {
83+
fprintf(stderr, "Unopened close bracket found!\n");
84+
return 1;
85+
}
8386
}
8487
}
8588

89+
if (!cfbf_stack_is_empty(stack)) {
90+
fprintf(stderr, "Unclosed open bracket found!\n");
91+
return 1;
92+
}
93+
8694
cfbf_destroy_stack(stack);
95+
96+
return 0;
8797
}
8898

8999
extern int cfbf_run_commands(cfbf_state *state)
90100
{
91101
uint32_t code_ptr = 0;
92-
cfbf_generate_jumps(state);
102+
103+
if (cfbf_generate_jumps(state) == 1) {
104+
// Unbalanced brackets. Return error
105+
return 1;
106+
}
93107

94108
while (code_ptr < state->commands_length) {
95109
switch (state->commands[code_ptr].token) {

src/cfbf.c

+3-1
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,9 @@ static int cfbf_open_file(char *filename)
9595
goto err;
9696
}
9797

98-
cfbf_run_commands(state);
98+
if (cfbf_run_commands(state) == 1) {
99+
goto err;
100+
}
99101

100102
// Clean up
101103
cfbf_destroy_state(state);

0 commit comments

Comments
 (0)