This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Can argv be NULL in C?


On 10/07/2016 10:40 AM, Yao Qi wrote:
Hi,
Luis has a GDB patch https://sourceware.org/ml/gdb-patches/2016-10/msg00137.html
which checks whether argv is NULL or not, because argv is NULL in
his env (aarch64-elf).

Can argv be NULL in C?

C requires that argv[argc] be null so argv cannot be null in
a conforming hosted implementation.  POSIX specifies (for execve)
that the argv pointer "is an array of character pointers" so calling
execve("a.out", (char*)0, ...) to arrange for argv to be null in main
would go against that requirement (and thus be undefined).  Main is
only specified in a hosted environment so if it's called or how in
a freestanding implementation is unspecified.

In C standard, argc and argv is specified
in "hosted environment", so argv can't be NULL in "hosted environment".
The program start-up is implementation-defined in "freestanding
environment".  Then, in practise, is bare-metal a "freestanding
environment"?  The bare-metal may still have its C library, like newlib,
so is it a "freestanding environment" or "hosted environment"?

It's considered freestanding by GCC when the -ffreestanding option
is specified (or some equivalent of it).  The freestanding
implementation can just happen to be the same (provide the same
features and guarantees) as some other implementation that GCC
considers hosted (or it can be almost the same with a few
small deviations, or even a lot of big gaps and differences).

In my experience, "bare metal" is usually used informally to mean
"something like freestanding" or a "subset of hosted" or even
"close to hosted except in these cases: ..." (with different people
having a different and often incomplete or incorrect understanding
of the formal term).

In this particular case, the C code has main function, so it expects
argument passing (argc and argv) from somewhere else, so my
understanding is that it is "hosted environment", and its argv must
be non-NULL.

Right.  In a hosted environment argv must not be null.  It's
up to the implementation to guarantee that for all conforming
programs.  If a program is non-conforming (e.g., it calls exceve
or its equivalent to start a program with a null argv) it's still
up to the implementation to decide what to do with it (it could
simply punt and pass the null through or it could substitute
an array of pointers for it with the first one set to null).

Martin


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]