Search code examples
c++parameter-passingvariadic-functions

C++ Memory violation error when trying to use function with variable of arguments


I want to create a function, that will log information to a file. This function needs to get some number of arguments and should iterate over them and print them to console. I have the following code:

void log(int argnum ...)
{
    va_list arguments;
    std::string argval;
    va_start(arguments, argnum);

    for (int i = 0; i < argnum; i++) {
        argval = va_arg(arguments, std::string);
        std::cout << argval;
    }

    va_end(arguments);
}

And when I try to call the function like this:

log(10, "somebody", "once", "told", "me",
        "the", "world", "is", "gonna", "roll", "me");

Visual Studio opens "memcpy.asm" and I get Access violation error. Any idea what is wrong?


Solution

  • Frankly, your code is a bit messy. You declared log to take parameters of type int:

    void log(int argnum ...)
    

    You then try to get them as std::strings:

    argval = va_arg(arguments, std::string);
    

    And you try to call the function with parameters of type int and const char[]. Moreover, you seem to have a misconeption about how to deal with the number of arguments.

    Most of the time, a variadic function template is the better option for vararg functions:

    #include <iostream>
    
    template <typename ...T>
    void log(const T& ... args)
    {
        (std::cout << ... << args) << '\n';
    }