2

I was playing around a bit with functions with variable arguments, and decided to make a function to create vectors with the arguments. My function for creating an int vector worked...

vector<int> makeIntVector(int numArgs, ...) {
    va_list listPointer;
    va_start(listPointer, numArgs);
    vector<int> made;
    for(int a = 0; a < numArgs; a++)
        made.push_back(va_arg(listPointer, int));
    va_end(listPointer);
    return made;
}

but not my function for creating a string vector:

vector<string> makeStringVector(int numArgs, string something, ...) {
    va_list listPointer;
    va_start(listPointer, something);
    vector<string> made;
    for(int a = 0; a < numArgs; a++)
        made.push_back(va_arg(listPointer, string));
    va_end(listPointer);
    return made;
}

which crashes the program. What am I doing wrong?

3 Answers 3

4

Attempting to pass a string as a varaidic parameter gives undefined behavior: "If the argument has a non-POD class type (clause 9), the behavior is undefined." (§5.2.2/7 of the standard).

Sign up to request clarification or add additional context in comments.

Comments

1

Variable arguments functions should not be used in C++.

The first argument is that they are only safe for PODs like int or char*, passing a non-POD C++ type has undefined behaviour.

Instead of creating a function with a long list of arguments, why don't you just create a vector and push back your strings into it?

2 Comments

why don't you just create a vector and push back your strings into it because it gets really tedious :P
C++11 seems to remedy this with its initializer lists. Hurrah!
0

I am not sure but I would investigate the fact that va_* are macros, int a "primitive" type while string is not. Maybe this causes the problem somewhere.

EDIT: g++ gives an important warning: cannot receive objects of non-POD type ‘struct std::string’ through ‘...’; call will abort at runtime

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.