Empty associative array crashes program

Jonathan M Davis jmdavisProg at gmx.com
Mon Apr 1 16:12:52 PDT 2013


On Monday, April 01, 2013 22:32:01 =?UTF-8?B?Ikx1w61z?=.Marques 
<luismarques at gmail.com>@puremagic.com wrote:
> I added a bug to the database, because the following code results
> in a segfault (DMD v2.062, OS X 10.8.3, 64-bit):
> 
> #!/usr/local/bin/rdmd
> 
> @safe:
> 
> void main()
> {
> int[string] a;
> a["foo"] = 0;
> a.remove("foo");
> assert(a != null); // segfault (not exception)
> }
> 
> Now I come here for some further clarifications. While it seems
> fairly clear to me that the assert should not crash the program
> with a segmentation fault (at least with @safe), is the assert
> actually true? (Is it even specified by the language if the AA
> can become null again, after removing the last item?)
> 
> Second, I didn't test this in other OSes, but assuming the bug is
> reproducible, am I actually the first one to trip on this issue?
> It seems too basic, but I didn't find a duplicate in the bug
> database.

The problem is that you're using != with null. Don't do that. If you want to 
check whether something is null, use the is operator:

assert(a !is null);

If you use == or !=, it's going to do compare the objects, not their 
pointers/references, and in the case of an AA, that means that it's going to 
dereference them both and compare their contents. And since null is well, 
null, dereferencing it results in a segfault.

If you try and compare objects with null with ==, you get an error. The 
compiler should probably do the same with AAs but apparently doesn't.

So, if there's a bug, it's the fact that the compiler allows the comparison in 
the first place. Otherwise, there's no bug here.

- Jonathan M Davis


More information about the Digitalmars-d mailing list