GC interpreting integer values as pointers
Ivo Kasiuk
i.kasiuk at gmx.de
Sat Oct 9 12:51:37 PDT 2010
Hi!
In my D programs I am having problems with objects not getting finalised
although there is no reference anymore. It turned out that this is
caused by integers which happen to have values corresponding to pointers
into the heap. So I wrote a test program to check the GC behaviour
concerning integer values:
----------------------------------------
import std.stdio;
import core.memory;
class C {
string s;
this(string s) { this.s=s; }
~this() { writeln(s); }
}
struct S {
uint r;
this(uint x) { r = x; }
}
class X {
C c;
uint r;
S s;
uint[int] a;
uint* p;
this() {
c = new C("reference");
new C("no reference");
r = cast(uint) cast(void*) new C("uint");
s = S(cast(uint) cast(void*) new C("struct"));
a[0] = cast(uint) cast(void*) new C("AA");
p = new uint;
*p = (cast(uint) cast(void*) new C("new uint"));
}
}
void main(string[] args) {
X x = new X;
GC.collect();
writefln("========== %s, %x, %x, %x, %x",
x.c.s, x.r, x.s.r, x.a[0], *x.p);
}
----------------------------------------
This writes:
new uint
no reference
========== reference, f7490e20, f7490e10, f7490df0, f7490dd0
AA
struct
uint
reference
So in most but not all situations the integer value keeps the object
from getting finalised. This observation corresponds to the effects I
saw in my programs.
I find this rather unfortunate. Is this known, documented behaviour? In
a typical program there are such integer values all over the place. How
should such values be stored to avoid unwanted interaction with the GC?
Thanks,
Ivo
More information about the Digitalmars-d-learn
mailing list