Empty Array is Null?

Steven Schveighoffer schveiguy at yahoo.com
Wed Mar 19 07:04:32 PDT 2008


"Brian White" wrote
> char[] array = "".dup;
> assert(array !is null);
>
> This will exit because the assert condition is false.
>
> Why is that?

Here is my guess:

The compiler does not allocate a piece of memory for "", and so the array 
struct for it looks like:

{ ptr = null, length = 0 }

If you dup this, it gives you the same thing (no need to allocate an array 
of size 0).

Now, here is the weird part.  The compiler does some magic with arrays.  If 
you are comparing an array with null, it changes the code to actually just 
compare the array pointer to null.  So, the the following code:

array !is null

is translated to:

array.ptr !is null

And this is why the program fails the assert.

The sucky part about all this is that if you have an empty array where the 
pointer is NOT null, then you get a different result (that array is not 
considered to be null)

So an array is null ONLY if the pointer is null.  An array is empty if the 
length is 0.  If you want to check for an empty array, just check that the 
length is 0.  If you want to make sure that the pointer is null (which 
implies the length is 0), then check against null.

So code like this looks weird to people who are used to C# or Java:

array = null;
array.length = 5; // you would expect a segfault here

Because array is really a struct with some compiler magic, the variable 
array itself can never truly be null.

Anyways, hope this helps.

-Steve 




More information about the Digitalmars-d-learn mailing list