Search code examples
c++stringiteratorsegmentation-fault

Segfault when inserting with iterator


The following code segfaults after the loop repeats 16 times. When debugging with gdb, *col is equal to 'a' except on the iteration when it segfaults, in which it suddenly becomes '\036'. This was tested on both gcc 6.30 and clang 3.8.1 on WSL Debian.

What could be the cause of this error?

#include <iostream>
#include <string>
int main(void) {
    std::string line = "";
    std::string::iterator col = line.begin();
    for (int i = 0;; i++) {
        std::cout << line << std::endl;
        std::cout << i << std::endl;
        line.insert(col, 'a');
    }
}

Edit: Yes, there is an infinite loop and I am aware of that. This is just for the MCVE.


Solution

  • After inserting elements into your string, the string may reallocating itself and then your iterator won't be point to the begin of your string and it won't be valid.

    So do this

    #include <iostream>
    #include <string>
    int main() {
        std::string line = "";
        std::string::iterator col = line.begin();
        for (int i = 0;; i++) {
            std::cout << line << std::endl;
            std::cout << i << std::endl;
            line.insert(col, 'a');
            col = line.begin();
        }
    }
    

    Note that this fixes the iterator issue only, but your infinite loop will extend your string infinitely until your program crashes.