can I pass argv from main to execv?
Asked Answered
S

1

5

The execv() function expects an array of NULL terminated strings but doesn't take the number of arguments. It uses a sentinel value (NULL pointer) to determine when the array ends.

The man page for execv() states...

The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a NULL pointer.

... so my question is....

I want to pass the argv from main() to execv().

Can I be assured that argv that comes into main is terminated by a NULL pointer? That is, can I be assured that argv[argc] == NULL or do I have to allocate my own char* array of size argc + 1 and put NULL in the argc index?

If I can be assured, is it documented somewhere?

Thanks, ~Eric

Semantics answered 16/5, 2012 at 13:34 Comment(0)
G
9

Yes. The argv vector is always NULL terminated.

The draft C99 standard states:

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.
Gladysglagolitic answered 16/5, 2012 at 13:34 Comment(7)
Can you cite a source for this?Mechanize
@ErnestFriedman-Hill From the standard, section 5.1.2.2.1 (see for example c0x.coding-guidelines.com/5.1.2.2.1.html)Atchison
lol... I'd like to mark the comment from @Adriano as the correct answer since I asked for a source. What needs to conform to this guideline?... the compiler?, the OS (Linux in this case), the shell?Semantics
And what if I called the OP's program using execve without terminating the command-line vector with a NULL? Would the standard comittee come and get me?Intangible
@Intangible no, they're more subtle and they'll make your program crash someday in the future when you'll be in the bathroom...Atchison
@Semantics to be conform is a compiler's duty. The way arguments are passed to the executable may be different from each OS - and actually it is.Atchison
@ErnestFriedman-Hill I added a quote of the draft C99 standard, I dare guess this language hasn't changed (since this isn't a new requirement).Gladysglagolitic

© 2022 - 2024 — McMap. All rights reserved.