yet another segfault - array out of bound is not caught by try catch

jfondren julian.fondren at gmail.com
Fri Sep 17 13:56:21 UTC 2021


On Friday, 17 September 2021 at 11:10:33 UTC, seany wrote:
> Compile with `dub build --compiler=ldc2 `. this should enable 
> array bound checking options.

By default, yes. run `dub -v build --compiler=ldc2` to see the 
exact commands that dub runs.

>     But should it not be caught by range error ?

Based on what you've said, yes it should.

> If I do `print l`in gdb, i find :
>         $1 = {length = 0, ptr = 0x0}
> With `print l[0]` i get: `Attempt to take address of value not 
> located in memory.`.

i.e., a segfault. null (or 0x0 (or 0)) isn't part of the memory 
addresses your program is allowed to access, so memory protection 
prevents the attempt to access it.

> What absolute rookie mistake am I committing?

 From this it doesn't sound like you are committing one, but if 
you're wanting bounds checking to be a normal part of program 
logic, and not something that only ever happens due to a 
programmer's error, then I think you're cutting against the grain 
of the language, where

- bounds checking is easily removed from all but @safe functions 
with normal flags

- flags exist to remove it from @safe functions also

- the *Error family of exceptions, including RangeError are not 
intended to be catchable

- raising and immediately catching an exception like this is 
slower and more verbose than an explicit test.

Rather than returning an empty array on an error and expecting a 
caller to catch RangeError, you could throw a normal exception on 
error, and then you have tools like `std.exception.ifThrown` to 
make dealing with that exception nicer.


More information about the Digitalmars-d-learn mailing list