>I was playing with args from command line, trying to understand how
>they work. But my little program shows up a strange behaviour that I
>don't understand. An extra beginning char appears.
There is no guarantee that the argument strings for argv[] appear
in order or without extra junk in between them. If you look at
memory beyond the end of the argument strings, you have invoked
the wrath of undefined behavior, and you deserve anything you
get (including smegmentation faults).
>For instance where I
>expected "abba" I get "aabba" and instead of "tony I get "ttony".
Don't expect that. You might get "supercalifragilisticexpialidociousabba".
>Can
>someone explain why this is so.
>Thanks
>Bob
>
>THE PROGRAM
>// argtest.c
>#include <stdio.h>
>
>main(int argc, char *argv[])
>{
> int i;
>
> for (i=0; i<argc; i++) {
> printf("argv= %d\n", argv);
> printf("argv[0]= %d\n", argv[0]);
> printf("*argv= %s\n", *argv);
> argv++;
> }
>
> char *g;
> for(i=0; i<20; i++) {
> g = (char*)(4006977+i);
It is a bad idea to hardcode addresses like this into your program.
The address might change on different runs of the same program. In
particular, on some platforms, the argv[] strings go at the top of
the stack (yes, I know C doesn't require a stack, but it doesn't
forbid one either), the address of the *end* of the strings may be
fixed, and the beginning may vary with the length of the strings.
If you mean g = argv[0]+i; , say so.
> printf(" %c\n", *g);
> }
>}
>
>
>
>THE OUTPUT
>C:\kern\find>gcc argtest.c -o argtest
>
>C:\kern\find>argtest abba tony
>argv= 4007056
>argv[0]= 4006977
>*argv= argtest
>argv= 4007060
>argv[0]= 4006986
>*argv= abba
>argv= 4007064
>argv[0]= 4006992
>*argv= tony
> a
> r
> g
> t
> e
> s
> t
>
> a
> a
> b
> b
> a
>
> t
> t
> o
> n
> y
>
Some platforms like to align the argv[] strings on even boundaries,
so this might account for what you are seeing. Try it with arguments
of abba, abba1, abba12, abba123, abba1234, abba12345, etc.
Gordon L. Burditt
|