dereferencing null

Jacob Carlborg doob at me.com
Fri Mar 2 02:56:52 PST 2012


On 2012-03-02 10:22, Peter Alexander wrote:
> On Friday, 2 March 2012 at 04:53:02 UTC, Jonathan M Davis wrote:
>> On Friday, March 02, 2012 05:37:46 Nathan M. Swan wrote:
>>> Am I correct that trying to use an Object null results in
>>> undefined behavior?
>>>
>>> Object o = null;
>>> o.opCmp(new Object); // segmentation fault on my OSX machine
>>>
>>> This seems a bit non-D-ish to me, as other bugs like this throw
>>> Errors (e.g. RangeError).
>>>
>>> It would be nice if it would throw a NullPointerError or
>>> something like that, because I spent a long time trying to find a
>>> bug that crashed the program before writeln-debugging statements
>>> could be flushed.
>>
>> It's defined. The operating system protects you. You get a segfault on
>> *nix and
>> an access violation on Windows.
>
> False.
>
> -----------------------
> import std.stdio;
>
> class Foo
> {
> final void bar()
> {
> writeln("I'm null!");
> }
> }
>
> void main()
> {
> Foo foo;
> foo.bar();
> }
> -----------------------
>
> % dmd test.d -O -release -inline
> % ./test
> I'm null!
> %
>
> -----------------------
>
> You only get an error if there is a memory access involved (vtable,
> member data etc.)
>

I never thought about that.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list