Max Frai
Max Frai

Reputation: 64276

Segfault in map

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" 

Upvotes: 1

Views: 1400

Answers (2)

dirkgently
dirkgently

Reputation: 111130

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) {
   // ....
}

Upvotes: 4

AndersK
AndersK

Reputation: 36082

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

Upvotes: 0

Related Questions