2010-08-22 6 views
1

Je ne comprends pas pourquoi ce Code échoue avec segfault:Segfault sur la carte

#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
texte string = ""; chaîne thatChange = ""; chaîne 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: dit Debugger:

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

Qu'est-ce que les en-têtes ou compilateur utilisez-vous? J'ai inséré et avec 'using namespace std;' et compilé avec gcc, pas de segfaults ici. – progo

+0

@progo mis à jour le code – Ockonal

+0

bien, ça ne plante pas pour moi. Quel compilateur utilisez-vous et quels drapeaux y passez-vous? – rasjani

Répondre

4
string thatChange = it->first ; 

Cette ligne appelle UB. Le it n'a jamais été initialisé jusqu'à présent. Vous devez initialiser ce comme suit:

it = tmp.begin(); 

et itérer sur tous les éléments de l'utilisation de la carte:

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

FWIW l'extrait de code compile et fonctionne très bien avec VS2010 donc si vous avez une erreur, le problème est probablement situé ailleurs.

+0

Le code est mis à jour, regardez-le, s'il vous plaît. – Ockonal