2013-10-22 62 views
1

我不明白爲什麼在delete[] *iopszString;, 有錯誤,你能幫我修復嗎?上次刪除時出錯[]

嘗試輸入:1 3 aaa

如果我省略了最後刪除[]這一切的作品,但因爲 爲了交換指針我需要刪除以前的點就沒有意義。 The code

// Notepad.cpp 

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 

// Method definition 
void addText(char** iopszString); 

void main() 
{ 

    // Const definition 
    int const ADD = 1; 
    int const UPDATE = 2; 
    int const DELETE = 3; 
    int const SAVE = 4; 
    int const EXIT = 5; 

    // Variable definition 
    int nUserCode; 

    // Code section 

    // Gets the user code 
    cout << "Enter the code: " << endl; 
    cin >> nUserCode; 

    // + "\0" so 1 minimum!!! 
    char* iopszString = new char[1]; 
    iopszString = ""; 

    // Runs until the exit code 
    while (nUserCode != EXIT) 
    { 
     // Checks the exit code 
     switch (nUserCode) 
     { 
      case ADD: 
      { 
       addText(&iopszString); 
       cout << iopszString << endl; 
       break; 
      } 
      case UPDATE: 
      { 

       break; 
      } 
      case DELETE: 
      { 

       break; 
      } 
      case SAVE: 
      { 

       break; 
      } 
      default: 
      { 
       cout << "Wrong code, try again" << endl; 

       break; 
      } 
     } 

     // Gets the user code 
     cout << "Enter the code: " << endl; 
     cin >> nUserCode; 
    } 

    // Delete the string cuz heap 
    delete[] iopszString; 
} 

void addText(char** iopszString) 
{ 
    // Variables definition 
    int nAddLength; 

    // Code section 

    // Gets the new length 
    cout << "Enter the length of the added string: " << endl; 
    cin >> nAddLength; 

    // Always remember - the length you want+1!! 
    char* szNewString = new char[nAddLength+1]; 

    // Gets the new string 
    cout << "Enter the new string which you want to add: " << endl; 
    cin >> szNewString; 

    // Creating a new string (result) 
    char* szResult = new char[nAddLength+1+strlen(*iopszString)]; 

    // Copies the old string to the new 
    strcpy(szResult, *iopszString); 
    strcat(szResult, szNewString); 

    // Deletes the new string cuz we already copied 
    delete[] szNewString; 

    // Exchange pointers 
    //strcpy(*iopszString, szResult); <--- never 

    // The problem! 
    delete[] *iopszString; 

    // Exchange pointer 
    *iopszString = szResult; 
} 
+0

什麼是錯誤消息è? – bstamour

+2

我強烈建議你開始使用'std :: string'並停止使用'void main'。 – chris

回答

6

bug是這兩行:

char* iopszString = new char[1]; 
iopszString = ""; 

您與new分配新的內存,您存儲在您的指針iopszString它的位置。然後,將字符串文字""的位置分配給該指針,以便指針本身的值改變。現在,它指向其他地方,指向您尚未分配給new並且您不擁有的內存位置。因此,您丟失了您分配的內存指針(內存泄漏),並且在指向""的位置的指針上調用delete[]時,它崩潰(因爲您不能使用delete[]釋放任何與new沒有分配的任何內容。

你大概意思寫:

char* iopszString = new char[1]; 
iopszString[0] = '\0'; 

這將只設置你分配給'\0',因此把它變成一個有效的,空的,0結尾的字符串的第一char的價值

+0

它解決了這個問題,謝謝! 但是,請您簡化說明嗎? –

+0

@desmondmiles我試圖改進解釋,希望它有幫助。 –

+0

哇,我真的明白了!謝謝 :-) –