Coalesce operator should box stack allocated values on the right side.
When a non-null value (e.g. a literal integer or a struct value) is on the right side of a coalesce expression, the code generated by the coalesce operator can produce dangling pointers.
For example the following code:
int? nn = null;
int n = nn ?? 42;
is essentially transformed into:
int? nn = null;
unowned int? _val_ = nn;
if (nn == null) {
_val_ = 42;
}
Which is incorrect, as it produces a dangling pointer to the stack allocated 42
.
Here is a test which demonstrates the issue, although note that it only fails on -02
, not -O0
:
void test_int () {
int? nn = null;
int? n = nn ?? 42;
assert (n == 42);
}
struct Foo {
public int n;
}
void test_struct () {
Foo df = { 42 };
Foo? nf = null;
Foo f = nf ?? df;
assert (f.n == 42);
}
void main () {
test_int ();
test_struct ();
}