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

Liam McGillivray yoshi.pit.link.mario at gmail.com
Sat Mar 9 07:49:52 UTC 2024


On Saturday, 9 March 2024 at 06:37:02 UTC, Richard (Rikki) Andrew 
Cattermole wrote:
> Something that I have noticed that you are still doing that was 
> pointed out previously is having a pointer to a class reference.
>
> Stuff like ``Tile* currentTile;`` when it should be ``Tile 
> currentTile;``
>
> A class reference is inherently a pointer.
>
> So when you checked for nullability in the foreach loop of 
> mission:
>
> ```d
> if (startTile.occupant !is null && (*startTile.occupant) !is 
> null) {
> ```

I think I'm starting to understand better. I was thrown off 
somewhere when I read that "references in D cannot be null". I 
tried doing some if-statements to determine if array objects are 
null, and some of them were.

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?


More information about the Digitalmars-d-learn mailing list