array !is null fails

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Tue Feb 13 10:50:27 PST 2007


BCS wrote:
> Frits van Bommel wrote:
>> 'null', when interpreted as an array, is an _empty_ array with the 
>> pointer being null.
>>
>> This allows it to be a reasonable default initializer for dynamic 
>> arrays, and means (arr == null) checks whether the array is empty.
> 
> Ok, I see that. But aren't the vast majority of comparisons ageist null 
> asking "Is this readable?" That is the meaning I would expect. Then 
> again it does bring in a corner case (length checked iff ptr!=null).
> 
> It's quite a bother though.
> 
> void fn(char[] c)
> {
> 
>     //works untill c.ptr == null && c.length != 0
> 
>     assert(c !is null);
>     writef("%s\n", c);
> }

I'd argue that if you have an array with a non-zero length but null 
pointer, you've already messed up somewhere. It should have been checked 
at whatever place sliced the null pointer. (The only way to obtain such 
an array would be either slicing a raw pointer or using pointer 
casts/unions to access memory as a different type than it actually is, 
right?)

And it'd get even worse if you take a non-empty slice from such an array 
that doesn't start at index 0. Then you have'd an array with non-zero 
length and non-null pointer that is nevertheless very much invalid, and 
without any way to detect it[1].



[1]: That is, short of indexing it and detecting the segfault/access 
violation caused, or resorting to system-dependent checks like "is it in 
the first page of memory".


More information about the Digitalmars-d-learn mailing list