title: Get optarg as a C++ string object
body: <p>I am using getopt_long to process command line arguments in a C++ application. The examples all show something like <code>printf("Username: %s\n", optarg)</code> in the processing examples. This is great for showing an example, but I want to be able to actually store the values for use later. Much of the rest of the code uses <code>string</code> objects instead of <code>char*</code> so I need to cast/copy/whatever the contents of optarg into a string.</p>
  
  <pre><code>string bar;
  while(1) {
      c = getopt_long (argc, argv, "s:U:", long_options, &amp;option_index);
      if (c == -1) break;
      switch(c)
          {
              case 'U':
                  // What do I need to do here to get
                  // the value of optarg into the string
                  // object bar?
                  bar.assign(optarg);
                  break;
          }
  }
  </code></pre>
  
  <p>The above code compiles, but when it executes I get an <code>Illegal instruction</code> error if I try to print out the value of bar using printf (it seems to work just fine for cout).</p>
  
  <pre><code>// Runs just fine, although I'm not certain it is actually safe!
  cout &lt;&lt; " bar: " &lt;&lt; bar &lt;&lt; "\n";
  
  // 'Illegal instruction'
  printf(" bar: %s\n", bar);
  </code></pre>
  
  <p>I do not know enough about command line debugging to better dig into what the illegal instruction might be. I had been running valgrind, but the sheer volume of memory errors that result from this error have made it difficult for me to pinpoint exactly what might be causing this error.</p>