Frozen
Frozen

Reputation: 15

varargs function crashing

I have a function that is supposed to take a variable number of arguments (using varargs) based on a format string:

void va(const char* name, const char* argformat, ...) {
    int numOfArgs = strlen(argformat);

    std::string buf = "asdf";

    va_list listPointer;
    va_start(listPointer, numOfArgs);
    char* blah;

    for(int i = 0; i < numOfArgs; i++) {
            switch (argformat[i]) {
                    case 's':
                            cout << va_arg(listPointer, char*) << endl;
                            break;
                    case 'i':
                            cout << va_arg(listPointer, int) << endl;
                            break;
                    case 'f':
                            cout << va_arg(listPointer, float) << endl;
                            break;
                    case 'b':
                            cout << va_arg(listPointer, bool) << endl;
                            break;
                    default:
                            break;
            }
    }

    va_end(listPointer);

    return;
}


int main() {
    va("fe", "sb", "asdf", true);

    return 0;
}

It crashes.

If I change
cout << va_arg(listPointer, char*) << endl;
to
cout << va_arg(listPointer, char) << end;

it prints "a".

What am I doing wrong?

Upvotes: 1

Views: 1201

Answers (1)

David
David

Reputation: 2871

It should be va_start(listPointer, argformat). va_start takes the last named parameter as its second argument. (Which technically means that you don't need to pre-calculate the length of the argument string at all — just iterate over the characters (iterating over the varargs as you go) until you get to the end of the string.)

Upvotes: 6

Related Questions