views:

878

answers:

3

I am using getopt_long to process command line arguments in a C++ application. The examples all show something like printf("Username: %s\n", optarg) 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 string objects instead of char* so I need to cast/copy/whatever the contents of optarg into a string.

string bar;
while(1) {
    c = getopt_long (argc, argv, "s:U:", long_options, &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;
        }
}

The above code compiles, but when it executes I get an Illegal instruction error if I try to print out the value of bar using printf (it seems to work just fine for cout).

// Runs just fine, although I'm not certain it is actually safe!
cout << " bar: " << bar << "\n";

// 'Illegal instruction'
printf(" bar: %s\n", bar);

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.

+6  A: 

You told printf that you were suppling a c style string (null terminated array of chars) when specifying %s, but you provided a string class instead. Assuming you are using std::string try:

printf("bar : %s\n", bar.c_str());
Trent
+5  A: 

printf() can't handle C++ strings. Use bar.c_str() instead.

dirkgently
I guess I'll have to put this in my list of important things to remember. Thanks!
Beau Simensen
+2  A: 
cout << " bar: " << bar << "\n";

is perfectly safe. What makes you think it might not be?

Ferruccio
Only because I realize that sometimes just because it runs that does not mean it is safe. :) Especially if it seems as though another method dies when using the same object.
Beau Simensen