I've the following code :
#include <stdio.h>
int main(int argc, char* argv[]){
int a = argv[1]?atoi(argv[1]):10;
int b = argv[2]?atoi(argv[2]):20;
printf("a = %d, b = %d\n", a, b);
return 0;
}
If I do not provide any command line inputs, the values in "a" and "b"
should be 10 and 20 respectively, but what happens instead is "a" gets value as 10 whereas "b" gets 0.
I cant understand why this is happening, since I am doing exactly same
thing in both cases.
Thanks.
The runtime (often thru crt0 & kernel) guarantees (per C99 or POSIX standards) that (for
main
's argumentsargc
&argv
) :argc
is positiveargv
is a valid nonNULL
pointer to an array ofargc+1
pointersargv[argc]
is theNULL
pointerfor each
i
between 0 andargc-1
included,argv[i]
is a (valid nonNULL
) pointer to a zero-terminated stringhence access to
argv[j]
withj>argc
(orj<0
) is undefined behavior (UB) - so explaining what happens is only possible by diving into implementation details...the valid
argv[i]
are not pointer aliases, so ifi
&j
are both between 0 andargc-1
included, andi
!=j
,argv[i]
!=argv[j]
therefore, your code is wrong when
argc==1
because accessingargv[2]
is forbidden (UB).You should code:
Be very scared of undefined behavior (see also the references here). Sadly, a program with UB might sometimes appear to "work" (that is might not crash). But at other times bad things may happen. So you should imagine the worst.
No, if you don't provide any command-line inputs, you're accessing beyond the end of the
argv
array and anything can happen (including your program crashing and burning).Your checks should be:
That's what
argc
is for, to tell you how many entriesargv
has in it that you can access.