www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Range violation

reply Vino <vino.bheeman hotmail.com> writes:
Hi All,

    Request your help on the below program, when I execute the 
program without passing any arguments it is throwing Range 
violation errors

Error:
core.exception.RangeError test.d(21): Range violation
----------------
0x004068CC
0x00408CF3
0x00408CB7
0x00408BB8
0x0040558F
0x74FE336A in BaseThreadInitThunk
0x770F98F2 in RtlInitializeExceptionChain
0x770F98C5 in RtlInitializeExceptionChain

Program:
import std.stdio;
import std.getopt;
import std.path;
import core.stdc.stdlib: exit;

void Test1() {
writeln("This is Test1");
}
void Test2() {
writeln("This is Test2");
}
void Test3() {
writeln("This is Help");
}

void main (string[] args) {
if (args.length < 1 || args.length > 2) {
	writeln(args[0].baseName, ":No Arguments Provided");
	exit(-1);
		}

string op = args[1];
getopt(args, std.getopt.config.caseInsensitive, 
std.getopt.config.stopOnFirstNonOption);

switch (op) {
case "dryrun" , "run" :
	Test1;
	Test2;
break;
case "help" :
	Test3;
	break;
default :
		 writefln("Unknown operation");
	 }
}

From,
Vino.B
Nov 24 2017
next sibling parent Timoses <timosesu gmail.com> writes:
On Friday, 24 November 2017 at 09:59:13 UTC, Vino wrote:

 if (args.length < 1 || args.length > 2) {
If args.length is 1 it will call
 string op = args[1];
However, args[1] accesses the second element. Due to above if statement args[1] can be called even though only args[0] exists.
Nov 24 2017
prev sibling parent Mike Parker <aldacron gmail.com> writes:
On Friday, 24 November 2017 at 09:59:13 UTC, Vino wrote:

 if (args.length < 1 || args.length > 2) {
 	writeln(args[0].baseName, ":No Arguments Provided");
 	exit(-1);
 		}
When you pass no arguments, this won't execute as args.length will still be 1, the only argument being the path to the executable -- args[0], of which you are apparently already aware. The if conditional should be this to test for no args: if(args.length == 1)
 string op = args[1];
Because the above conditional passes when you pass no args, this causes a range violation since args[1] doesn't exist.
Nov 24 2017