2 years ago

#70458

test-img

nimesh00

Different behaviour of segmentation fault for different number of arguments in a variadic function

I am using a variadic function definition to handle multiple arguments of the same type (std::vector<[data_type]>). As the termination criterion, I am using the try-catch to use the exception that is thrown when the function va_arg() tries to read more variables than are passed while calling. When the number of arguments is 1-3 or 5+ (total while calling), I am getting the std::bad_alloc, which I am able to catch and successfully stop further calls to va_arg() and continue. But when I pass 4 (exactly!!) variables, I get the core dumped message and the program execution aborts. I do not understand why there is different behavior only in the case of 4 variables. Can anyone explain to me why this is happening? I am using cmake version 3.16.3 on Ubuntu 20.04. I am attaching the sample function definition below:

template<typename T>
    void func(std::vector<T> data1d, ...) {
        /* Reading the variable number of arguments */
        va_list valist;
        // Starting the variable argument list pointer
        va_start(valist, data1d);
        // Storage container for each argument
        std::vector<T> vaitem;

        // Vector to store all the data being extracted from all the arguments
        std::vector<std::vector<T>> cols;
        // Storing the data in the first argument
        cols.push_back(data1d);
        do {
            try {
                vaitem = va_arg(valist, std::vector<T>);
            } catch (std::exception& e) {
                break;
            }
            cols.push_back(vaitem);
        } while (true);
        // Indicates the variable argument list end
        va_end(valist);
}

c++

exception

variadic-functions

0 Answers

Your Answer

Accepted video resources