Skip to content

Commit 2c824f4

Browse files
authored
cgen: fix code generation when the function returns mut fixed array (fix #20366) (#20367)
1 parent 7c9f9f8 commit 2c824f4

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

vlib/v/gen/c/cgen.v

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5284,7 +5284,7 @@ fn (mut g Gen) return_stmt(node ast.Return) {
52845284
g.autofree_scope_vars(node.pos.pos - 1, node.pos.line_nr, true)
52855285
g.write('return ')
52865286
}
5287-
if expr0.is_auto_deref_var() {
5287+
if expr0.is_auto_deref_var() && !fn_return_is_fixed_array {
52885288
if g.fn_decl.return_type.is_ptr() {
52895289
var_str := g.expr_string(expr0)
52905290
g.write(var_str.trim('&'))
@@ -5303,7 +5303,12 @@ fn (mut g Gen) return_stmt(node ast.Return) {
53035303
if fn_return_is_fixed_array && !node.types[0].has_flag(.option) {
53045304
g.writeln('{0};')
53055305
if node.exprs[0] is ast.Ident {
5306-
g.write('memcpy(${tmpvar}.ret_arr, ${g.expr_string(node.exprs[0])}, sizeof(${g.typ(node.types[0])})) /*ret*/')
5306+
typ := if expr0.is_auto_deref_var() {
5307+
node.types[0].deref()
5308+
} else {
5309+
node.types[0]
5310+
}
5311+
g.write('memcpy(${tmpvar}.ret_arr, ${g.expr_string(node.exprs[0])}, sizeof(${g.typ(typ)})) /*ret*/')
53075312
} else if node.exprs[0] in [ast.ArrayInit, ast.StructInit] {
53085313
if node.exprs[0] is ast.ArrayInit && node.exprs[0].is_fixed
53095314
&& node.exprs[0].has_init {

vlib/v/tests/return_fixed_array_test.v

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,14 @@ fn test_without_alias() {
2121
a := return_fixed_array()
2222
assert a == [1, 2, 3]!
2323
}
24+
25+
// for issue 20366: returns mut fixed array
26+
fn returns_mut_fixed_array(mut fixed_array [3]int) [3]int {
27+
return fixed_array
28+
}
29+
30+
fn test_returns_mut_fixed_array() {
31+
mut fixed := [3]int{}
32+
res := returns_mut_fixed_array(mut fixed)
33+
assert res == [0, 0, 0]!
34+
}

0 commit comments

Comments
 (0)