SSJX.CO.UK
Browser Games | Cybiko | Amiga | Applications | Windows Games | Java Area | Test Area | Guides | Site Map

Out Of Bounds - D

Introduction

This is part of a series testing each of the languages I use to see how good they are at catching simple array out of bounds errors.

These tests check for the following:

The Code

The following was tested using DMD 2.0.88.1 :

import std.stdio;

void main()
{
	const int pa=3;
	int pb=4;
	int[3] array=[1,2,3];
		
	// #1. Simple so should be an easy catch - CT: CAUGHT
	array[3]=97;
	
	// #2. This is a constant so should also be an easy catch - CT: CAUGHT
	array[pa]=98;

	// #3. Variable index but does start outside - CT: FAILED
	array[pb]=99;

	// #4. Looping through array - CT: FAILED
	foreach(i;0..5)
	{
		writeln(array[i]);
	}
}

Test 1 - Default Settings

By default checks are on so this is the only test. The compiler picked up errors #1 and #2, surprised it did not catch #4.

With #1 and #2 commented out, running the above gives Range violation errors.

Extra

To fix error #4, we could use a range based loop instead:

	// #4. Looping through array - Better version
	foreach(value;array)
	{
		writeln(value);
	}

Summary

I've mentioned on this site before that I am a fan of D. I like the fact that these sensible checks are enabled by default and do not require some arcane knowledge to enable. I did expect #4 to be caught though, the compiler is very smart so thought it would realise that the loop goes outside the array boundary. Hopefully this will be fixed in the future!

11/01/20