0

I am getting a weird string for my argv[2], when I run this program without any inputs. Why isn't argv[2] undefined? TERM_PROGRAM=Apple_T <- That's what I get. I'm wondering if this has something to do with running it on a mac?

if(argv[2]) {
    sscanf(argv[2], "%lf", &argWind);
    sscanf(argv[2], "%20s",  str);
    sprintf(str2, "%lf", argWind);
    printf("String: %s, %lf", str, argWind);
    int len;
    len = strlen(str);
    str2[len] = '\0';

    if(strcmp(str, str2)){
        printf("\nError: you entered a non-numeric entry for wind speed\n");
        return 0;
    }
} 
Derek Halden
  • 2,223
  • 4
  • 17
  • 26
  • Possibly it's because you're on a mac. You should be able to test the len(sys.argv) to get the number of parameters passed, if you've not got a second parameter then it *should* be empty... perhaps it's reading the NULLPTR. – Michael Stimson Jan 28 '15 at 02:17
  • 5
    You must use `argc` to determine which elements of `argv[]` are valid. Anything in `argv[]` at index beyond `argc-1` is just stuff that happens to be there in memory. `argc` tells you how many elements in `argv[]` are valid. Note that the command name itself is in `argv[0]`. That's just how it works. It has nothing to do with the Mac. – lurker Jan 28 '15 at 02:17
  • This happens when I run it without arguments. – Derek Halden Jan 28 '15 at 02:17
  • 1
    `argv` is simply defined as an array. It's your responsibility to check `argc` for the number of elements in that array and not exceed them. `argv` is zero-based, so if `argc == 2` then the available elements of `argv` are 0 and 1. If you acess `argv[2]`, you're going past the end of the array and accessing random (uninitialized) memory and what you get as a result is undefined. – Ken White Jan 28 '15 at 02:18
  • 1
    If `argc <= 1` and you are reading `argv[2]` you are invoking undefined behavior. – 5gon12eder Jan 28 '15 at 02:18
  • Thanks everyone! that answers all of my questions! – Derek Halden Jan 28 '15 at 02:20

3 Answers3

7

Undefined behaviour is undefined. Anything could happen. In this case it looks like you're running past argv and into the third (less well known and certainly nonstandard) parameter of main, commonly called envp. Relevant link.

Community
  • 1
  • 1
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
1

argv[2] is the third parameter of the command line like this code, argc is the number of parameters:

int main(int argc, char const *argv[])
{
  int i = 0;
  for (; i < argc; ++i)
  {
     printf("%d -> %s\n", i, argv[i]); 
  }
  return 0;
}

See the process:

F:\so>tcc test.c

F:\so>test.exe a b c
0 -> test.exe
1 -> a
2 -> b
3 -> c

test.exe is the first, a is the second, b is third, c is the fourth. If you run test.exe whitout other parameters, it will say argv[2] means b here is not defined.

lqhcpsgbl
  • 3,694
  • 3
  • 21
  • 30
1

you'd better check "argc" firstly, then you can choose to use the valid "argv"

Xiaofei HAN
  • 159
  • 1
  • 2