2013-05-17 57 views
0

我與我的構造的目標是:strcat的錯誤「未處理的異常。」

打開讀取到一個特定的字符串(「%%%%%」)之間存在的一切文件 放在一起每次讀取將行添加到變量(歷史記錄) 將最終變量添加到類型爲char(_stories) 的雙指針關閉該文件。

但是,當我使用strcat時,程序崩潰。但我不明白爲什麼,我試了好幾個小時沒有結果。 :/

下面是構造函數代碼:

Texthandler::Texthandler(string fileName, int number) 
     : _fileName(fileName), _number(number) 
{ 
    char* history = new char[50]; 

    _stories = new char*[_number + 1]; // rows 
    for (int j = 0; j < _number + 1; j++) 
    { 
     _stories[j] = new char [50]; 
    } 
     _readBuf = new char[10000]; 

    ifstream file; 
    int controlIndex = 0, whileIndex = 0, charCounter = 0; 

    _storieIndex = 0; 

    file.open("Historier.txt"); // filename 
    while (file.getline(_readBuf, 10000)) 
    { 
     // The "%%%%%" shouldnt be added to my variables 
     if (strcmp(_readBuf, "%%%%%") == 0) 
     { 
     controlIndex++; 
     if (controlIndex < 2) 
     { 
      continue; 
     } 
    } 

    if (controlIndex == 1) 
    { 
     // Concatenate every line (_readBuf) to a complete history 
     strcat(history, _readBuf); 
     whileIndex++; 
    } 

    if (controlIndex == 2) 
    { 
     strcpy(_stories[_storieIndex], history); 

     _storieIndex++; 
     controlIndex = 1; 
     whileIndex = 0; 
     // Reset history variable 
     history = new char[50]; 

    } 
} 
file.close(); 
} 

我也試過沒有結果字符串流..

編輯:忘了發佈錯誤消息: 「未處理的異常在0x6b6dd2e9(msvcr100d .dll)在Step3_1.exe中:0xC00000005:訪問衝突寫入位置0c20202d20。「 了一個名叫「strcat.asm」文件打開..

問候 羅伯特

回答

2

你們有過的棧上某處的緩衝區溢出,用事實證明你的指針之一是0c20202d20(一幾個空格和一個-符號)。

這可能是因爲:

char* history = new char[50]; 

是不是你想要什麼就擺在那裏(或者它以其他方式不正確設置爲C字符串,用\0字符終止)足夠大。

我不能完全肯定,爲什麼你認爲每個高達10K的多個緩衝區可以串聯成一個50字節的字符串:-)

1

strcat運行在空值終止char陣列。在線路

strcat(history, _readBuf); 

history是未初始化的,因此不保證有一個空終止符。您的程序可能會讀取超出分配的內存,尋找'\0'字節,並嘗試在此處複製_readBuf。超出分配給history的內存的寫入會調用未定義的行爲,並且崩潰很可能發生。

即使您添加了空終止符,history緩衝區比_readBuf短得多。這使得內存溢出的可能性很大 - 你需要至少與_readBuf一樣大。

或者,因爲這是C++,爲什麼不使用std::string而不是C風格的char數組?

+0

謝謝你們!我通過你的回答解決了這個問題! :) – Cyrix

+0

很高興有幫助。既然你是一個新用戶,我希望你不要介意,如果我指出你對[接受答案]的一些筆記(http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer -工作) – simonc