2011-10-20 4 views
0

Je reçois un défaut de segmentation et je n'ai aucune idée de comment le déboguer! Il se produit après la création du tableau MyString, c'est-à-dire le tableau créé sans aucun problème.erreur de segmentation C++

void ConcatTest() 
{ 
    cout << "\n----- Testing concatentation on MyStrings\n"; 

    const MyString s[] = 
      {MyString("outrageous"), MyString("milk"), MyString(""), 
      MyString("cow"), MyString("bell")}; 

    for (int i = 0; i < 4; i++) { 
      cout << s[i] << " + " << s[i+1] << " = " << s[i] + s[i+1] << endl; 
     } 
} 

donc je pense qu'il peut être quelque chose dans la façon dont je l'opérateur surchargée + ici:

MyString operator+(MyString str1, MyString str2) 
{ 
    MyString resultStr = MyString(); 
    delete [] resultStr.pString; 
    resultStr.pString = new char[strlen(str1.pString) + strlen(str2.pString) + 1]; 
    MyString temp = MyString(); 
    delete [] temp.pString; 
    temp.pString = new char[strlen(str1.pString) + 1]; 
    strcpy(temp.pString, str1.pString); 
    delete [] str1.pString; 
    str1.pString = new char[strlen(str1.pString) + strlen(str2.pString) + 1]; 
    strcpy(str1.pString, temp.pString); 
    strcat(str1.pString, str2.pString); 
    strcpy(resultStr.pString, str1.pString); 
    return resultStr; 
} 

Toute aide ou des conseils seraient appréciés!

Répondre

1

Vous essayez de delete str1.pString à mi-chemin dans votre méthode +.

mais str1 est passé comme const MyString, ce qui pointe vers une chaîne statique dans le programme. Vous ne pouvez pas libérer ce!

probablement la cause. Vous ne devez pas modifier str1 ou str2 dans votre opérateur.

Si j'ai bien compris votre programme, vous voulez modifier la chaîne d'entrée. Pour ce faire, vous devez construire votre MyString initial avec un réelchar[] tableau de caractères, plutôt qu'une chaîne entre guillemets statique comme "scandaleux".

donc,

char* ch1="outrageous"; // ch1 points to a nonmutable memory area 
char* str1 = new char[strlen(ch1)]; // str1 now points to a mutable region of memory 
strcpy(str1,ch1); // that mutable region now contains the static string 

MyString string1 = new MyString(str1); // this string is now writable/changeable 

cette string1 est maintenant mutable;

+0

Oui, un "const" pourrait être le bienvenu pour str1 et str2 dans la déclaration de fonction. –

+0

Merci pour l'explication! –