title: Setting argv[0] to longer value than currently allocated
body: <p>I am writing a program in C that spawns loads of processes and that should report their state via argv[0] so while calling <code>ps</code> it's easy to see what's going on.</p>
  
  <p>I am aware that initially argv[0] comes with certain memory allocated, that contains the program name (in most cases).</p>
  
  <p>I need however to set much longer string than 20 bytes that contain my program name. My status can be 80-100 characters long.</p>
  
  <p>I made some tests and if I memcpy this longer string into argv[0] it "works for me" but I am afraid that I will start writing into unowned memory and cause segfault which is unacceptable.</p>
  
  <p>How can I safely resize memory allocated for argv[0]?</p>
  
  <p>Sample code:</p>
  
  <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  char* generate_really_long_program_name() {
    return strdup("here is something that generates really long program name\0");
  }
  
  
  int main (int argc, char *argv[])
  {
    printf("Current argv[0] length: %zu\n", strlen(argv[0]));
  
    char* my_program_name = generate_really_long_program_name();
    strncpy(argv[0], my_program_name, strlen(my_program_name)); // Can this segfault?
    free(my_program_name);
  
    printf("New argv[0] length: %zu\n", strlen(argv[0]));
  
    return 0;
  }
  </code></pre>
  
  <p>Sample output:</p>
  
  <pre><code>$ ./argv
  Current argv[0] length: 6
  New argv[0] length: 57
  </code></pre>