Looks like dereferencing a null pointer, but is ok???

Max Samuha maxter at i.com.ua
Thu Sep 14 12:53:20 PDT 2006


On Wed, 13 Sep 2006 02:26:56 +0300, Georg Wrede
<georg.wrede at nospam.org> wrote:

>I seldom need slices... which reminds me:
>
>import std.stdio;
>import std.gc;
>
>void main()
>{
>	int[] ia = new int[100];
>	int[] ib = ia[2..4];
>
>	ib[0] = 666;
>	ib[1] = 777;
>
>	delete ia;
>
>	std.gc.fullCollect();
>
>	char[] ca = new char[400];
>
>	writefln("ib[0]=%d and ib[1]=%d", ib[0], ib[1]);
>}
>
>which of course gives
>
>ib[0]=-1 and ib[1]=-1
>
>as totally expected -- by everyone else except the poor programmer, 
>whose code is larger than this example. :-)
>
>Time for Dlint, at least for the programmer who forgot to adhere to the 
>Bovine rule.

And you even don't need to trigger the garbage collection. delete will
free the whole memory block occupied by the array.

If you want the slice to the array to remain valid, replace 'delete
ia' with 'ia = null'.this will set the array data pointer to null
without freeing the memory and ib will still point to the array's
memory block preventing the garbage collector from collecting it. If
you want to delete the array explicitly, duplicate the slice
beforehand. 

Please correct me if i'm wrong.



More information about the Digitalmars-d-learn mailing list