Providing implicit conversion of - memory-safety
Renato
renato at athaydes.com
Tue Jan 23 19:27:26 UTC 2024
On Tuesday, 23 January 2024 at 17:54:25 UTC, bachmeier wrote:
> On Tuesday, 23 January 2024 at 12:34:38 UTC, Nick Treleaven
> wrote:
>
>> But I'm strongly in favour of catching any bugs at
>> compile-time (and have been since before I discovered D). I
>> just object to anyone trying to downgrade the importance of
>> automated memory-safety checking.
>
> I'm not downgrading the importance of memory safety. All I'm
> saying is that you can't sell D as a safe language if has bugs
> like this.
>
> Here's a reduced version of one of the most bizarre bugs I've
> dealt with in any language. The only reason I didn't move on to
> another language was because I was too busy at the time.
>
> The code allows for initial values if the index is less than 0,
> otherwise it returns the element.
>
> ```
> import std;
>
> double value(T)(T index, double * x) {
> if (index - 5 < 0) {
> return 0.0;
> } else {
> return x[index-5];
> }
> }
>
> void main() {
> double[] v = [1.1, 2.2, 3.3];
> // Works
> writeln(value(3, v.ptr));
> // Lucky: program segfaults
> writeln(value(v.length, v.ptr));
> }
> ```
>
> I noticed this behavior only because the program crashes. Once
> I figured out what was going on, I realized that the thousands
> of lines of code I had already written needed to be checked and
> possibly rewritten. If only I had a compiler to do that for me.
This code seems to be doing everything it can to run into
undefined behaviour, though?
Why is `index` of a type T that has no requirements at all (when
the implementation quite clearly wants `size_t`, or at least an
unsigned numerical value)? Why is it using a pointer for x when
clearly you intend to use it as a slice? You probably have
context that I don't, but I would never expect this sort of code
to be anywhere near @safe :D
More information about the Digitalmars-d-learn
mailing list