Just a friendly reminder about using arrays in boolean conditions

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Nov 19 01:22:56 UTC 2024


On Sunday, November 17, 2024 3:17:18 PM MST Steven Schveighoffer via 
Digitalmars-d wrote:
> On Sunday, 17 November 2024 at 21:50:18 UTC, kdevel wrote:
> > My question is: Is it possible that a valid D program gets into
> > a
> > state where an array has ptr == null and length > 0? If so, how?
>
> Yes, the compiler uses it:
>
> ```d
> struct S
> {
>      int x;
> }
>
> void main()
> {
>      auto i = typeid(S).initializer;
>      assert(i.ptr is null);
>      assert(i.length > 0);
> }
> ```
>
> For a type that is all 0, the compiler builds `initializer` to be
> a null array with a length. This signifies to the runtime that
> the type is all 0 initializer, but has a specific length. This
> allows saving binary space by not storing a bunch of 0s.

Does this actually appear in the wild at all, or is this really something
that's just restricted to what the compiler is doing? Obviously, based on
your example, if you use initializer, you have this problem, but is this
something that arrays in general need to worry about? There's definitely
code out there (including in Phobos) which uses ptr to avoid bounds checks
when it already knows that the indices it's using are in bounds, and if code
like that runs into an array with a null ptr but non-zero length, it's going
to segfault. Array code in general just assumes that that's not a thing, and
this is the first I've ever heard of it being a thing.

- Jonathan M Davis





More information about the Digitalmars-d mailing list