-2

My code:

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int BinaryToDecimal(int n)
{
    int ans = 0;
    int x = 1;

    while (n > 0)
    {
        int y = n % 10;
        ans = ans + x * y;
        x = x * 2;
        n = n / 10;
    }
    return ans;
}

int DecimalToBinary(int num)
{
    vector<int> vect;

    while (num > 0)
    {
        vect.push_back(num % 2);
        num = num / 2;
    }
    int s = vect.size();
    int i = s - 1;
    for (i = s - 1; i >= 0; i--)
    {
        cout << vect.at(i);
    }
    return vect.at(i);
}

int main()
{
    int a, b;
    cout << "Enter first number: " << endl;
    cin >> a;
    cout << "Enter second number: " << endl;
    cin >> b;

    int a_deci = BinaryToDecimal(a);
    int b_deci = BinaryToDecimal(b);

    int sum = a_deci + b_deci;

    DecimalToBinary(sum);
    cout << endl;
    return 0;
}    

Output:

Enter first number: 
10101
Enter second number:
11010
101111terminate called after throwing an instance of 'std::out_of_range'what():  vector::_M_range_check: __n (which is 18446744073709551615) >= this->size() (which is 6)

What does this error message mean and how do I fix it?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • When the loop terminates, `i == -1`. `return vect.at(i);` then exhibits undefined behavior by way of accessing an index out of bounds. – Igor Tandetnik Jun 28 '22 at 21:18
  • 2
    Unrelated: [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – user4581301 Jun 28 '22 at 21:30
  • A coworker of mine wrote up a nice blog post on this subject: [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Eljay Jun 28 '22 at 21:50
  • @IgorTandetnik accessing out of bounds with `.at()` throws an exception, it isn't UB . – M.M Jun 28 '22 at 22:13

1 Answers1

1

After this for loop

for (i = s - 1; i >= 0; i--)
{
    cout << vect.at(i);
}

the variable i is equal to -1.

So the next call of the member function at with the value equal to -1 (that yields a very big number of the unsigned type std::vector<int>::size_type)

return vect.at(i);

throws the exception.

It seems you need to return from the function the whole vector elements of which will represent a number in the binary form.

Instead of the container std::vector<int> it will be better to use std::bitset.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335