Search code examples
linuxcommand-lineglibc

Would argc ever be passed less than 1


I'm developing my own version of getopt() in assembly and trying to get my head wrapped around this snippet, specifically line 476

    if (argc < 1)
       return -1;

As the normal calling convention would be something like this;

    int c = getopt( argc, argv, "vm:drx:");

and assuming the programmer hasn't done anything with argc before hand, the only reason I can think it would be there is that some flavor of Linux, possibly non POSIX compliant would'nt pass argv[0] application path & name. Therefore, argc could be zero. Is there any credence to this conjecture?

Of the 12 times this variable is used in this procedure, it's only ever asserted or copied, never modified and not referenced at all in the two levels of procedure before this.


Solution

  • Consider this:

    #include <stdio.h>
    #include <unistd.h>
    
    int main(int argc, char* argv[])
    {
            execve("./testargc", NULL, NULL);
    }
    

    And this program:

    #include <stdio.h>
    
    int main (int argc, char* argv[])
    {
            printf("%d\n", argc);
    }
    

    The first one execs the 2nd one with no arguments. The pathname is not passed in and as a result argc is 0.