compiler crashes when looking for palindromes

This code looks for numbers that are palindromes in both decimal and binary. Function isDecPal checks if number is decimal palindrome and returns true if it is, and false if it isn't. isBinPal does the same.

Both functions convert number to string, reverses it, and checks if it's the same. When converting to binary, I use vector to store binary numbers in.

Now when I set the interval from 1 to 1 000 000 and calculate the sum of palindromic numbers, loop goes to 3113 and then the compiler crashes so bad I have to restart my codeblocks. What's going on?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
  #include <iostream>
#include <cmath>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

bool isDecPal (int number)
{
    string strnumber;
    stringstream convert;
    convert << number;
    convert >> strnumber;
    string reStrnumber = string(strnumber.rbegin(), strnumber.rend());
    if (strnumber==reStrnumber) return true;
    else return false;
}

bool isBinPal (int number)
{

    vector <int> vnum2;
    int vsize=0;

    while (number>=1) {
        if (number%2==0) {
            vnum2.push_back(0);
        }
        else vnum2.push_back(1);
        number=number/2;
        vsize++;
    }
    vsize--;
    string str2num;

    for (int i=0; i<=vsize; i++)
    {
        stringstream convert;
        convert << vnum2[i];
        convert >> str2num[i];
    }
    string restr2num=string(str2num.rbegin(), str2num.rend());
    if (restr2num==str2num) return true;
    else return false;
}


int main()
{
double sum=0;
for (int i=1; i<=1000000; i++) {
    if ((isDecPal(i)==1) and (isBinPal(i)==1)) {
        sum=sum+i;
    }
}

cout << sum;
}


On line 35 you define an empty string.

On line 41 you try to access non-existent elements of that string.
Topic archived. No new replies allowed.