Skip to content

Commit

Permalink
cgen: fix premature variable release by autofree (vlang#20731)
Browse files Browse the repository at this point in the history
  • Loading branch information
GGRei authored Feb 5, 2024
1 parent 4b46461 commit e48e28d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
4 changes: 3 additions & 1 deletion vlib/v/gen/c/cgen.v
Original file line number Diff line number Diff line change
Expand Up @@ -2970,7 +2970,9 @@ fn (mut g Gen) autofree_scope_vars2(scope &ast.Scope, start_pos int, end_pos int
// continue
// }
// if v.pos.pos > end_pos {
if obj.pos.pos > end_pos || (obj.pos.pos < start_pos && obj.pos.line_nr == line_nr) {
if obj.pos.pos > end_pos
|| (obj.pos.pos < start_pos && obj.pos.line_nr == line_nr)
|| (end_pos < scope.end_pos && obj.expr is ast.IfExpr) {
// Do not free vars that were declared after this scope
continue
}
Expand Down
19 changes: 19 additions & 0 deletions vlib/v/slow_tests/valgrind/if_expr_autofree_optional.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
fn main() {
out := if temp := f('') {
temp
} else if temp := f('something') {
temp
} else {
return
}

assert out[0] == 104
assert out[1] == 105
}

fn f(s string) ?[]u8 {
if s == '' {
return none
}
return [u8(104), 105]
}

0 comments on commit e48e28d

Please sign in to comment.