Why does string.insert (iterator, char) work six times in a row, but not seven? (C ++)

The code:

#include <iostream>
#include <string>

using namespace std;

string expand(string mask);

int main()
{
    string tiny = "blah blah [a-e] blah blah";
    string lengthy = "blah blah [a-i] blah blah";
    cout << expand(tiny) << endl;
    cout << expand(lengthy) << endl;
    return 0;
}


string expand(string mask)
{
    int i, range;

    /* find the first bracket, grab start letter */
    unsigned int bracket = mask.find("[");
    char start = mask[bracket + 1];

    /* point iterator at first bracket */
    string::iterator here = mask.begin();
    here += bracket;

    /* find second bracket, calculate ascii range */
    range = mask[bracket + 3] - mask[bracket + 1];

    /* kill brackets and their contents*/
    mask.erase(here, here + 5);

    /*** This loop causes an error on the 7th iteration ****/
    for(i = 0; i <= range; i++)
        mask.insert(here, (start + range) - i);

    return mask;
}

Output:

matt @Callandor: ~ / prog / tempVer $ g ++ test.cpp -o play

matt @Callandor: ~ / prog / tempVer $. / play

blah blah abcde blah blah

blah blah defghi blah blah

* glibc detected * ./play: free (): invalid next size (fast): 0x08353068

======= Backtrace: ========= / lib / libc.so.6 (+ 0x6c501) [0x5b5501] ...

When trying to use string :: insert (iterator, char), I encounter some kind of odd behavior; I have inside the "for" loop where I don't move the iterator at all, the loop just inserts characters. It works fine if I have six or less characters to insert, but fail for seven or more.

(. ), , . , .

( ):

for(i = 0; i < 6; i++)
    mask.insert(here, (start + range) - i);
    cout << mask << endl;

for(i = 0; i < 7; i++)
    mask.insert(here, (start + range) - i);
    cout << mask << endl;

, .

- , ?

+3
5

, .

, . here , , , . undefined, here , reset .

+9

, , , , here .

+2

std::basic_string<T>::insert . here insert. undefined , :)

, here = mask.insert(here, (start + range) - i); .

, , , , find :)

. , , -, , , , insert, n, n .

+1

, , , , .

0

, 6, 7.

, , , , .

, . , .

, "" 6 , , , .

5 , , , , , " ".

, , , (), push_back(), , , .

0

Source: https://habr.com/ru/post/1792419/


All Articles