Skip to content

Commit 78c5946

Browse files
committed
cgen: fix uninitialized interface bug (closes #17372)
1 parent 4e73f87 commit 78c5946

2 files changed

Lines changed: 33 additions & 0 deletions

File tree

‎vlib/v/gen/c/auto_str_methods.v‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,7 @@ fn (mut g Gen) gen_str_for_interface(info ast.Interface, styp string, typ_str st
400400
mut fn_builder := strings.new_builder(512)
401401
clean_interface_v_type_name := util.strip_main_name(typ_str)
402402
fn_builder.writeln('${g.static_non_parallel}string indent_${str_fn_name}(${styp} x, ${ast.int_type_name} indent_count) { /* gen_str_for_interface */')
403+
fn_builder.writeln('\tif (x._typ == 0 && x._object == NULL) return _S("nil");')
403404
for typ in info.types {
404405
sub_sym := g.table.sym(ast.mktyp(typ))
405406
if g.pref.skip_unused && sub_sym.idx !in g.table.used_features.used_syms {
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Test for bug #17372: Uninitialized interface type field gives runtime error when accessing it
2+
// Expected behavior: print "nil" instead of causing a runtime crash
3+
4+
interface Boo {}
5+
6+
struct Foo {
7+
boo Boo
8+
}
9+
10+
@[noinit]
11+
struct Bar {
12+
boo Boo
13+
}
14+
15+
fn test_uninitialized_interface_field_str() {
16+
// Printing uninitialized interface field should return "nil", not crash
17+
s := '${Foo{}.boo}'
18+
assert s == 'nil', 'Expected "nil" for uninitialized interface, got "${s}"'
19+
}
20+
21+
fn test_uninitialized_interface_field_in_struct_str() {
22+
// Struct containing uninitialized interface should also work
23+
foo := Foo{}
24+
s := '${foo}'
25+
assert s.contains('boo: nil'), 'Expected struct str to contain "boo: nil", got "${s}"'
26+
}
27+
28+
fn test_noinit_struct_with_interface_field() {
29+
bar := Bar{}
30+
s := '${bar.boo}'
31+
assert s == 'nil', 'Expected "nil" for noinit struct interface field, got "${s}"'
32+
}

0 commit comments

Comments
 (0)