Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does `execvp` take a `char *const argv[]`?
    primarykey
    data
    text
    <p>I'm wondering if there is a reason between two exec functions differing in <code>const</code>-ness, of if this is just a bug in the Single Unix Spec:</p> <p>Excerpting from the Linux manpage, which appears to align with the <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/fexecve.html">Single Unix Specification</a>, here are a two versions of <code>exec</code>:</p> <blockquote><code><b>int execlp(const char *</b>file<b>, const char *</b>arg<b>, ...);<br> int execvp(const char *</b>file<b>, char *const </b>argv<b>[]);</b></code></blockquote> <p><code>execlp</code> takes its arguments as <code>const char *</code>, and it takes two or more of them. <code>const</code> in C is a promise that the function will not change the pointed-to data, in this case the actual characters (<code>char</code>) that make up the string.</p> <p><code>execvp</code> instead takes its arguments as an array of pointers. However, instead of an array of pointers to <code>const char *</code> as you'd expect, the <code>const</code> keyword is in a different spot—and this matters quite a bit to C. <code>execvp</code> is saying it may well modify the characters in the strings, but it promises not to modify the array—that is, the pointers to the strings. So, in other words,</p> <pre class="lang-c prettyprint-override"><code>int fake_execvp(const char *file, char *const argv[]) { argv[0] = "some other string"; /* this is an error */ argv[0][0] = 'f'; /* change first letter to 'f': this is perfectly OK! */ /* ⋮ */ } </code></pre> <p>In particular, this makes it hard (technically, prohibited) to call execvp using C++'s <code>std::string</code>'s <code>to_cstr()</code> method, which returns <code>const char *</code>.</p> <p>It seems like <code>execvp</code> really ought to take <code>const char *const argv[]</code>, in other words, it ought to promise not to do either of the above changes.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload