2016-11-09 135 views
-1

我想弄清楚爲什麼這段代碼不能正常工作。我想爲超過250,000字的字典文件分配內存。內存分配工作正常。但是空閒的內存不會。而且,老實說,我不知道爲什麼。它在釋放期間中斷。以下是代碼。 謝謝。在C++中分配和釋放內存

#include <iostream> // For general IO 
    #include <fstream> // For file input and output 
    #include <cassert> // For the assert statement 
    using namespace std; 

    const int NumberOfWords = 500000; // Number of dictionary words 
       //if i change to == to exact number of words also doesnt work 
    const int WordLength = 17;  // Max word size + 1 for null 

    void allocateArray(char ** & matrix){ 
     matrix = new char*[NumberOfWords]; 

     for (int i = 0; i < NumberOfWords; i++) { 
      matrix[i] = new char[WordLength]; 

       // just to be safe, initialize C-string to all null characters 
       for (int j = 0; j < WordLength; j++) { 
        matrix[i][j] = NULL; 
       }//end for (int j=0... 
     }//end for (int i... 
    }//end allocateArray() 

    void deallocateArray(char ** & matrix){ 
      // Deallocate dynamically allocated space for the array 
      for (int i = 0; i < NumberOfWords; i++) { 
       delete[] matrix[i]; 
      } 
      delete[] matrix; // delete the array at the outermost level 
    } 

    int main(){ 
    char ** dictionary; 

    // allocate memory 
    allocateArray(dictionary); 

    // Now read the words from the dictionary 
    ifstream inStream; // declare an input stream for my use 
    int wordRow = 0; // Row for the current word 
    inStream.open("dictionary.txt"); 
    assert(!inStream.fail()); // make sure file open was OK 

    // Keep repeating while input from the file yields a word 
    while (inStream >> dictionary[wordRow]) { 
     wordRow++; 
    } 
    cout << wordRow << " words were read in." << endl; 

    cout << "Enter an array index number from which to display a word: "; 
    long index; 
    cin >> index; 
    // Display the word at that memory address 
    cout << dictionary[index] << endl; 

    deallocateArray(dictionary); 

    return 0; 
} 
+1

什麼 '遊' 的意思是添加

#include <iomanip> 

?它崩潰,或不編譯,它提供了哪個錯誤信息? –

+0

另外,考慮用memset代替'for(int j = 0; j

+0

@DenisSheremet停止並且VS中的cmd窗口不會關閉。 – Art

回答

1

的問題是在下面的行:

while (inStream >> dictionary[wordRow]) { 

上有輸入線長度沒有限制並且應用覆蓋字符串緩衝區中的至少一個。我想解決這個問題是這樣的:

while (inStream >> std::setw(WordLength - 1) >> dictionary[wordRow]) { 

請不要忘記與setd::setw聲明

+0

你的建議部分工作。控制檯在最後關閉。但是,在這個改變後,程序顯示了7000多個單詞。 (換文後26.3萬文件中的文字爲270,000)。 – Art

+0

你是什麼意思的'控制檯關閉在最後'? – GMichael

+0

我的意思是程序到達「return 0;」在main()中; – Art