views:

56

answers:

3

Hello, I can't understand why does this code fail with segfault:

#include <cstdlib>
#include <iostream>
#include <map>
#include <string>

using namespace std;

int main(int argc, char** argv) {

    map <string, string> temp;
    map <string, string>::iterator it;

S
string text = ""; string thatChange = ""; string whatChange = "";

    getline (cin, text);


    while (true)
    {
        getline (cin, thatChange);
        if (thatChange == "-1")
            break;

        getline (cin, whatChange);
        temp.insert(pair <string, string> (thatChange, whatChange));
    }

    for (int i = 0; i < temp.size(); i++)
    {
        string thatChange = it->first ; // thatChange
        string whatChange = it->second; // whatChange
        it++;

        int index = text.find(thatChange);
        text.erase(index, thatChange.size());
        text.insert(index, whatChange);
    }

    cout << "text\n"<< text;

    return 0;
}

UPD: Debugger says:

No source available for "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string() at 0x7ffff7b75928" 
A: 

Please post a full code example that compiles, not just a snipped.

Gabriel Schreiber
A: 

FWIW the code snippet compiles and runs fine with VS2010 so if you got an error the problem is probably located elsewhere.

Anders K.
Code is updated, look at it, please.
Ockonal
+3  A: 
string thatChange = it->first ;

This line invokes UB. The it has never been initialized so far. You ought to initialize this as follows:

it = tmp.begin();

and to iterate over all the elements of the map use:

for (map<string, string>::const_iterator f = temp.begin(), e = temp.end;
     f != e;
     ++f) {
   // ....
}
dirkgently