core dump error

Dec 6, 2019 at 6:26pm
closed account (1Ck93TCk)
I'm running into this error that I can't figure out. The program runs and outputs everything correctly, but then I get this at the end:

terminate called after throwing an instance of 'std::out_of_range;
what(): basic_string::replace: __pos (which is 21) > this ->size(). Aborted (core dumped)

I understand that the issue is with the size going out of bounds on the line with the replace statement. But I'm looking at it, and I'm just not seeing why it's acting this way. Can anyone shed some light?

Thank you!
jmb

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
//Triangle upper right
//This program draws a triangle in a square
//12-4-19 
//Sources:

#include <iostream>
#include <string>

using namespace std;

const int MAX = 30;

void drawTriangle(string triangle, string star, int size, int &indent);

int main()
{
    string star = "*";
    string triangle;
    int size;
    int indent = 0;


    cout << "This program accepts a square size from the user " << endl;
    cout << "and draws a triangle in the upper right corner " << endl;
    cout << "of the square." << endl;
    cout << endl;
    cout << "Enter what size you would like the square to be (less than 30): ";
    cin >> size;

        while(size > 30 || size < 1)
        {
            cout << "Out of range. Try again: ";
            cin >> size;
        }
    drawTriangle(triangle, star, size, indent);

}
void drawTriangle(string triangle, string star, int size, int &indent)
{
    int i = 0;
    int j = 0;
    int rows = 0;

    for(rows = 0; rows < size; rows++)
    {
        for (i = 0; i < size; i ++)
        {
            triangle.insert(0, size, ' ');
            triangle.replace(indent, 1, size - indent, '*');
            indent++;
            cout << triangle;
            triangle.clear();
            cout << endl;
        }
    }
}
Dec 6, 2019 at 6:49pm
indent starts at zero and tries to go up to (size * size), because it is incremented size times on every row, and there are size rows

triangle.replace(indent, 1, size - indent, '*');

What happens when indent becomes bigger than size? Something bad.
Dec 6, 2019 at 7:32pm
closed account (1Ck93TCk)
Oooooh,

I see it. I think I've got it. Thank you for the fast reply!

jmb
Topic archived. No new replies allowed.