Use-after-scope bug in Phobos unittest, how to fix?
Johan
j at j.nl
Mon May 15 18:55:09 UTC 2023
Hi all,
I found a bug in Phobos typecons unittest:
https://github.com/ldc-developers/phobos/blob/6c83b490f7d6c66bf430e5249dae608848d3ac2c/std/typecons.d#LL7088C1-L7108C46
```d
pure @system unittest
{
foreach (MyRefCounted; AliasSeq!(SafeRefCounted, RefCounted))
{
MyRefCounted!int* p;
{
auto rc1 = MyRefCounted!int(5);
p = &rc1; // assigns reference to variable in inner
scope...
assert(rc1 == 5);
assert(rc1._refCounted._store._count == 1);
auto rc2 = rc1;
assert(rc1._refCounted._store._count == 2);
// Reference semantics
rc2 = 42;
assert(rc1 == 42);
rc2 = rc2;
assert(rc2._refCounted._store._count == 2);
rc1 = rc2;
assert(rc1._refCounted._store._count == 2);
}
assert(p._refCounted._store == null); // use after scope!
```
The bug is uncovered when optimization and variable lifetime are
considered with LDC.
I see that the test is trying to prove that the MyRefCounted
dtors are run correctly when the scope ends. However, the way
that this is tested is technically UB as far as I understand the
D lang spec (although I cannot find explicit mention of variable
lifetimes, please help...).
I can simply disable optimization for this unittest function
(ldc.attributes.optStrategy), but would rather not.
Ideas?
thanks,
Johan
More information about the Digitalmars-d
mailing list