Why am I getting segfaults when doing `foreach` with arrays of references?

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Sat Mar 9 07:57:25 UTC 2024


On 09/03/2024 8:49 PM, Liam McGillivray wrote:
> But that begs the question; why? Don't dynamic arrays always start with 
> a length of 0? If the array was only extended when valid objects were 
> appended using the append operator |~=|, and none of those objects were 
> deleted (as I the destructor was never called), why would some of the 
> array elements be null?

The default initialization state of a pointer (regardless of type) in D 
is null.

I.e.

```d
Object[] array;
array.length = 2;
array[0] = new Object;

assert(array[0] !is null);
assert(array[1] is null);

array ~= new Object;

assert(array[0] !is null);
assert(array[1] is null);
assert(array[2] !is null);
```


More information about the Digitalmars-d-learn mailing list