Fdsfds Fdsfds
Fdsfds Fdsfds

Reputation: 1

Exception Unhandled c++ va_arg

this is the code, get the min using a function with multiple variables.

#include<iostream>
        #include <stdarg.h>
        #include <math.h>
        using namespace std;
        float minim(int n,...);
        int main(void)
        {
            float v[10];
            int n;
            cout << "Introduceti numerele reale: " << endl;
            for (int i = 0; i < 10; i++)
            {
                cout << "v[" << i + 1 << "]= ";
                cin >> v[i];
            }
            cout << "\n";
            cout << "Minimul dintre primele 7 numere introduse este: " << minim(7, v[0], v[1], v[2], v[3], v[4], v[5], v[6]) << endl;
            cout << "Minimul dintre ultimele 3 numere introduse este: " << minim(3, v[7], v[8], v[9]) << endl;
            cout << "Minimul dintre cele 10 numere este: " << minim(2, minim(6, v[0], v[1], v[2], v[3], v[4], v[5], v[6]), minim(3, v[7], v[8], v[9])) << endl;
        }
        float minim(int n, ...)
        {
            float element, minim=0;
            va_list args;
            va_start(args, n);
            for (int i = 0; i < n; i++)
            {
                element = va_arg(args, float);
                if (i = 0)
                    minim = element;
                else if (element < minim)
                    minim = element;
            }
            va_end(args);
            return minim;
        }

Unhandled exception thrown: read access violation. args was 0x600004. at the line element = va_arg(args, float);

Upvotes: 0

Views: 40

Answers (1)

Goswin von Brederlow
Goswin von Brederlow

Reputation: 12342

Compiler says it all:

$ g++ --std=c++20 -O2 -W -Wall -o foo foo.cc
foo.cc: In function ‘int main()’:
foo.cc:9:17: warning: unused variable ‘n’ [-Wunused-variable]
    9 |             int n;
      |                 ^
foo.cc: In function ‘float minim(int, ...)’:
foo.cc:29:23: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
   29 |                 if (i = 0)
      |                     ~~^~~
In file included from foo.cc:2:
foo.cc:28:40: warning: ‘float’ is promoted to ‘double’ when passed through ‘...’
   28 |                 element = va_arg(args, float);
      |                                        ^
foo.cc:28:40: note: (so you should pass ‘double’ not ‘float’ to ‘va_arg’)
foo.cc:28:40: note: if this code is reached, the program will abort

Note: the i = 0 means this is an endless loop and will try to get an infinite number of arguments. That's probably the crash you see.

Upvotes: 4

Related Questions