No bounds checking for dynamic arrays at compile time?

bearophile bearophileHUGS at lycos.com
Thu Dec 13 01:38:17 PST 2012


Chris Cain:

> Consider:
>
> void main() {
>    int[] arr;
>    foo(arr);
>    arr[0] = 2;
> }
>
> Should this spit out a compile time error? You can't say 
> without knowing what 'foo' does. If I say foo means this:
>
> void foo(int[] array) {
>    int len;
>    readf(" %s", &len);
>    array.length = len;
> }
>
> Well, now it depends on what len is.

That program seems to have a bug, unless the signature of foo 
becomes (ref int[]). A bit smarter compiler should see that.


> In general, the compiler can't know ahead of time whether 
> accessing a dynamic array will be out of bounds without running 
> it.

Right, but there are several cases where a little smarter 
compiler is able to see at compile-time that something bad is 
present in the code.

----------------------

Walter:

> You'd have to add data flow analysis to the front end, and 
> you'd reap very little useful error messages out of it.

 From my usages of a lint tool in C, that's able to perform that 
flow analysis, I have seen that it spots several out of array 
bound mistakes in the code statically.


> Note that this example came from a tutorial, not real code.

It's from a tutorial, and I agree well tested code usually 
doesn't have those problems, but when you are writing code you 
often do some mistakes (that later you fix), so having a compiler 
that helps a little is useful to speed up the coding and 
debugging itself. It's better to spot mistakes as early as 
possible.

See also what I have suggested time ago:
http://d.puremagic.com/issues/show_bug.cgi?id=6884
http://d.puremagic.com/issues/show_bug.cgi?id=6883

To spot at compile-time situations like:


void main() {
     int[5] x;
     x[$] = 1;
     enum size_t n = 2;
     x[$ + n] = 2;
}


void main() {
     int[] x = new int[5];
     x[$] = 1; // easy
     x[x.length] = 1; // idem
     enum size_t n = 2;
     x[$ + n] = 2; // not too much hard if n is unsigned
     x[x.length + n] = 2; // idem
}

Bye,
bearophile


More information about the Digitalmars-d mailing list