93

Given the standard definition for the main program:

int main(int argc, char *argv[]) {
   ...
}

Under which circumstances can argc be zero on a POSIX system?

15
  • 13
    I'd try int execv(const char *path, char *const argv[]); with an argv containing only a NULL pointer to find out ;)
    – user2371524
    Apr 13, 2018 at 12:46
  • 4
    the C standard allows the argc to be < 1, if it is exactly 0 I found it here port70.net/~nsz/c/c11/n1570.html#5.1.2.2.1p2
    – Achal
    Apr 13, 2018 at 12:49
  • 13
    Given the widely used if (argc < x) { fprintf(stderr, "Usage: %s ...", argv[0]); }, I definitely see the practical relevance of this question :)
    – user2371524
    Apr 13, 2018 at 12:59
  • 3
    would be an effective dupe of stackoverflow.com/questions/8113786/… if not for the precise stipulation that it has to be about POSIX Apr 13, 2018 at 13:01
  • 5
    @mtraceur argv[0] || "" is unfortunately an int...
    – user2404501
    Apr 13, 2018 at 20:44

6 Answers 6

108

Yes, it is possible. If you call your program as follows:

execl("./myprog", NULL, (char *)NULL);

Or alternately:

char *args[] = { NULL };
execv("./myprog", args);

Then in "myprog", argc will be 0.

The standard also specifically allows for a 0 argc as noted in section 5.1.2.2.1 regarding program startup in a hosted environment:

1 The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

int main(void) { /* ... */ } 

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

int main(int argc, char *argv[]) { /* ... */ }

or equivalent; or in some other implementation-defined manner.

2 If they are declared, the parameters to the main function shall obey the following constraints:

  • The value of argc shall be nonnegative.
  • argv[argc] shall be a null pointer.

...

Note also that this means that if argc is 0 then argv[0] is guaranteed to be NULL. How printf treats a NULL pointer when used as the argument to a %s specifier is not spelled out in the standard however. Many implementations will output "(null)" in this case but it's not guaranteed.

11
  • 8
    @SylvainLeroux You (and others reading this answer later) may find it interesting to know, in addition to the documentation about the general case, that as of a couple of years ago, one system that aims to be POSIX-compliant has in fact made it impossible to invoke programs with argc == 0: OpenBSD.
    – mtraceur
    Apr 13, 2018 at 22:28
  • @mtraceur, out of curiosity: what does OpenBSD do, if you call exec with only the path and no arguments for the program? (fail? copy the path to the zeroth argument?)
    – ilkkachu
    Apr 13, 2018 at 22:48
  • 1
    @ilkkachu On OpenBSD execve fail with the error EINVAL if you invoke it with an empty argv. It's easy to miss in the execve manual page, as the error behavior for that condition is only mentioned in the list of possible errors at the bottom.
    – mtraceur
    Apr 14, 2018 at 0:25
  • @mtraceur Interesting, as FreeBSD does allow it.
    – dbush
    Apr 14, 2018 at 20:17
  • 1
    @mtraceur the NULL in varargs part. 0 would be an int not pointer. Apr 17, 2018 at 1:08
29

To add to the other answers, there is nothing in C (POSIX or not) preventing main() from being called as a function within the program.

int main(int argc, int argv[]) {
    if (argc == 0) printf("Hey!\n");
    else main(0,NULL);

    return 0;
}
1
  • 13
    ... Huh. I thought that was specifically prohibited, but it turns out only C++ does that and C is fine with it.
    – Daniel H
    Apr 13, 2018 at 22:33
25

Yes, it can be zero, meaning that argv[0] == NULL.

It's a convention that argv[0] is the name of the program. You can have argc == 0 if you launch yourself the binary, like with execve family and don't give any argument. You can even give a string that is nowhere near to be the program name. That's why using argv[0] to get the name of the program is not entirely reliable.

Usually, the shell where you type your command-line always add the program name as the first argument, but again, it's a convention. If argv[0] == "--help" and you use getopt to parse option, you will not detect it because optind is initialized to 1, but you can set optind to 0, use getopt and "help" long option will show up.

long story short : It's perfectly possible to have argc == 0 (argv[0] is not really special by itself). It happen when the launcher doesn't give argument at all.

16
  • "but you can set optind to 0" -- Not portably. POSIX says "If the application sets optind to zero before calling getopt (), the behavior is unspecified."
    – user743382
    Apr 13, 2018 at 13:48
  • 7
    Well, '--help' is a legit filename, so, why argv[0] can't be '--help' ?
    – Tom's
    Apr 13, 2018 at 14:24
  • 3
    The wording "it's a convention" is slightly inaccurate. A program not following that "convention" is not conforming to POSIX (read the "Rationale" part of the documentation). So while it is very possible to do something different, doing so is non-conforming. Whether or not this is something one should expect to happen (because it is possible) or not is up to debate. I'm in the "don't support broken software" team.
    – Damon
    Apr 13, 2018 at 15:20
  • 6
    @CharlesDuffy: That's how we got stuck with tag soup (HTML quirks mode), email spam (SMTP abuse), and the regular internet blackholing of random countries (bad BGP pushes). If somebody is violating the standard, and there is no historical reason for allowing them to do so, then you should fail. Loudly.
    – Kevin
    Apr 13, 2018 at 17:37
  • 1
    @Damon The rationale is not normative and it would not be the first time the rationale makes a claim that is not backed up by the normative text. I am unable to find any normative text that says passing a null pointer for the program name is non-conforming.
    – user743382
    Apr 13, 2018 at 22:18
17
+100

Early proposals required that the value of argc passed to main() be "one or greater". This was driven by the same requirement in drafts of the ISO C standard. In fact, historical implementations have passed a value of zero when no arguments are supplied to the caller of the exec functions. This requirement was removed from the ISO C standard and subsequently removed from this volume of POSIX.1-2017 as well. The wording, in particular the use of the word should, requires a Strictly Conforming POSIX Application to pass at least one argument to the exec function, thus guaranteeing that argc be one or greater when invoked by such an application. In fact, this is good practice, since many existing applications reference argv[0] without first checking the value of argc.

The requirement on a Strictly Conforming POSIX Application also states that the value passed as the first argument be a filename string associated with the process being started. Although some existing applications pass a pathname rather than a filename string in some circumstances, a filename string is more generally useful, since the common usage of argv[0] is in printing diagnostics. In some cases the filename passed is not the actual filename of the file; for example, many implementations of the login utility use a convention of prefixing a ( '-' ) to the actual filename, which indicates to the command interpreter being invoked that it is a "login shell".

Also, note that the test and [ utilities require specific strings for the argv[0] argument to have deterministic behavior across all implementations.

Source


Can argc be zero on a POSIX system?

Yes but it would not be strictly conforming to POSIX.

6
  • 2
    Does "POSIX system" imply "every single program on the system is a 'Strictly Conforming POSIX Application"? Genuine question - I don't know the pedantic semantics of the standard on this matter. I do know that I can take a system that is certified as a POSIX System and trivially write/run a program on it that isn't a "Strictly Conforming POSIX Application", and I'm not sure if it's the intended meaning of the POSIX standard to say that the system becomes non-conforming the moment any non-strictly-conforming third-party application is installed on it?
    – mtraceur
    Apr 13, 2018 at 19:26
  • @mtraceur Isn't that a completely separate question? Not sure if you expect it to be answered in this comment thread or if you want the extra information added to the answer. Both seems weird.
    – pipe
    Apr 13, 2018 at 20:24
  • @mtraceur if your program run on linux, you can expect that you program will run under Posix standard, the responsibility is going to the program that execute you to be Posix conforming, aka your shell in general. That say, nothing prevent a shell to not being posix conforming but I highly doubt that someone will use it ;), if your distribution of linux allow non conforming Posix program in their packets, is not the problem of linux.
    – Stargateur
    Apr 13, 2018 at 20:37
  • @pipe I'm asking for clarification on that point because I think it would determine whether the implicit reasoning in this answer applies to the question, or is misleading: The answer "Yes but it would not be strictly conforming to POSIX" seems to me to logically imply that the mere presence (or perhaps execution) of any program that can run char *nothing = { 0 }; execve(*prog, nothing, nothing) on a system would lead to POSIX declaring that system "not strictly conforming". This strikes me as unlikely to be what the POSIX standard intended?
    – mtraceur
    Apr 13, 2018 at 21:33
  • @Stargateur Can we really expect that? Let's say we write a C program that is a "strictly conforming POSIX application", and run it on Linux, or FreeBSD, or one of the most recent HP-UX or Solaris systems (on any other Unix that's POSIX-conformant). So we've got our strictly conforming POSIX application on a POSIX system: Now some other developer comes along, writes a small program that calls our program with the execve system call - but that developer makes a small mistake and calls us without any arguments: Is it fair to say the system as a whole is no longer "strictly conforming POSIX"?
    – mtraceur
    Apr 13, 2018 at 21:43
4

whenever you want to run any executable like ./a.out it will have one argument thats the program name. But It is possible to run a program with argc as zero in Linux, by executing it from another program that calls execv with an empty argument list.

for e.g

int main() {
    char *buf[] = { NULL };
    execv("./exe", buf); /* exe is binary which it run with 0 argument */
    return 0;
}
4

TL;DR: Yes, argv[0] can be NULL, but not for any good/sane reason I know of. However, there are reasons not to care if argv[0] is NULL, and to specifically allow the process to crash if it is.


Yes, argv[0] can be NULL on a POSIX system, if and only if it was executed without any arguments.

The more interesting practical question is, should your program care.

The answer to that is "No, your program can assume argv[0] is not NULL", because some system utilities (command-line utilities) either do not work or work in a non-deterministic fashion, when argv[0] == NULL, but more importantly, there is no good reason (other than stupidity or nefarious purposes) why any process would do that. (I'm not sure if the standard usage of getopt() also fails then — but I would not expect it to work.)

A lot of code, and indeed most examples and utilities I write, begin with the equivalent of

int main(int argc, char *argv[])
{
    if (argc < 2 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
        printf("Usage: %s [ -h | --help ]\n", argv[0]);
        /* ... print usage ... */
        return EXIT_SUCCESS;
    }

and this is reasonable and acceptable, because there is no good reason for a process to exec another process without providing at least the command path being executed, i.e. execlp(cmd, cmd, NULL) rather than execlp(cmd, NULL).

(However, I can think of a few nefarious reasons, like exploiting timing race windows related to pipe or socket commands: an evil process sends an evil request via an established Unix domain socket, and then immediately replaces itself with an authorized victim command (run without any arguments, to ensure minimum start-up time), so that when the service getting the request checks the peer credentials, it sees the victim command, instead of the original evil process. It is, in my opinion, best for such victim commands to crash hard and fast (SIGSEGV, by dereferencing a NULL pointer), rather than try and behave "nicely", giving the evil process a larger time window.)

In other words, while it is possible for a process to replace itself with another but without any arguments causing argc to be zero, such behaviour is unreasonable, in the strict sense that there is no known non-nefarious reason to do so.

Because of this, and the fact that I love making life hard for nefarious and uncaring programmers and their programs, I personally will never add the trivial check, similar to

static int usage(const char *argv0)
{
    /* Print usage using argv0 as if it was argv[0] */
    return EXIT_SUCCESS;
}

int main(int argc, char *argv[])
{
    if (argc < 1)
        return usage("(this)");
    if (argc < 2 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))
        return usage(argv[0]);

    /* argv[0] and argv[1] are non-NULL, argc >= 2 */

except if requested by someone with a particular existing use case in mind. And even then I'd be a bit suspicious, wanting to verify the use case myself first.

8
  • Do you consider checking programs to see if they were written with careful attention to corner-cases a good/sane/non-nefarious usecase? Because I regularly invoke every new program I use with zero arguments for a quick estimate of what sort of behavior I can expect from the program in other "shouldn't happen / shouldn't be done" circumstances. I even have a command-line tool so I can do it quickly and easily without having to write code every time for it (though admittedly I wrote the tool more for controlling the zeroth argument in general).
    – mtraceur
    Apr 13, 2018 at 19:22
  • @mtraceur: In general yes, but in this particular case no. This is simply because I think the no-argument case has no proper use cases (that I know of), but at least one nefarious use case; and the nefarious use case is best defeated by the program dying as early as possible (and due to SIGSEGV is a good way of doing that). I do not think that checking the no-argument case is any kind of an indication of whether the program otherwise behaves sanely in "should not occur" -type of situations. Apr 13, 2018 at 20:58
  • @mtraceur: One example is write() (low-level C function; a syscall wrapper in Linux) returning a negative value other than -1. It simply should not occur, so most programmers do not test for it. Yet, it has occurred in Linux, due to a kernel filesystem bug, for writes over 2 GiB. (Currently, writes are limited to just under 2 GiB at the syscall level, to avoid similar bugs in other filesystem drivers.) My own code is the only one I have seen that checks that case too. (I treat it as an EIO error.) Yet, as I said, I have decided not to check for argc == 0 in my code. Apr 13, 2018 at 21:01
  • I've decided to +1 your answer, our discussion aside, because I think your perspective and approach is valuable. I wish more people thought so critically and carefully about whether to handle (or not to handle) the full range of corner-cases that might happen.
    – mtraceur
    Apr 13, 2018 at 22:03
  • Correct me if I'm wrong: Does the C standard actually guarantee any sane behavior, let alone dying-as-early-as-possible, if you dereference argv[0] when argc == 0? Isn't that dereferencing a null pointer, which in turn means undefined behavior? Are you comfortable trusting that every implementation of C your code will be ran against will perform something reasonable?
    – mtraceur
    Apr 13, 2018 at 22:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.