2012-07-21 42 views
0

退出我孤立的問題來驗證碼:函數調用多次導致程序與神祕的錯誤

#include <windows.h> 
using namespace std; 

const wchar_t* readLine(int posX, int posY, int len) { 
    wchar_t* wcharFromConsole = new wchar_t[len]; 
    COORD pos = {posX,posY}; 
    DWORD dwChars; 
    ReadConsoleOutputCharacterW(GetStdHandle(STD_OUTPUT_HANDLE), 
    wcharFromConsole, // Buffer where store symbols 
    len,  // Read len chars 
    pos, // Read from row=8, column=6 
    &dwChars); // How many symbols stored 
    wcharFromConsole [dwChars] = L'\0'; // Terminate, so string functions can be used 
    return wcharFromConsole; 
} 

int main() { 
    for (int i = 0; i <= 63; i++) { 
    readLine(0,0,80); 
    } 
    system("pause"); 
} 

的事情是,如果循環運行不到63倍它的工作原理,如果字符的長度從裝控制檯不到80這也適用...我不知道這裏發生了什麼。是否有任何資源我必須明確地關閉......但爲什麼,如果一個函數關閉了,它應該關閉它的所有資源。但是這裏發生的事情我不知道,編譯的程序(沒有任何錯誤)在默默地退出system()函數之前退出。還有其他的錯誤代碼,因爲我從我的項目中刪除了部分代碼,有時候是程序要求以不尋常的方式終止程序,而在其他時候程序被停止並停止接受鍵盤輸入。

- 編輯:

我已經根據建議更新代碼:

#include <iostream> 
#include <windows.h> 

using namespace std; 

const wchar_t* readLine(int posX, int posY, int len) { 
    wchar_t* wcharFromConsole = new wchar_t[len]; 
    COORD pos = {posX,posY}; 
    DWORD dwChars = 0; 
    if(!ReadConsoleOutputCharacterW(GetStdHandle(STD_OUTPUT_HANDLE), 
    wcharFromConsole, // Buffer where store symbols 
    len,  // Read len chars 
    pos, // Read from row=8, column=6 
    &dwChars)) // How many symbols stored 
    { 
    cout << "ReadConsoleOutputCharacterW failed, code" << GetLastError() << endl; 
    } 
    wcharFromConsole [dwChars] = L'\0'; // Terminate, so string functions can be used 
    return wcharFromConsole; 
} 

int main() { 
    for (int i = 0; i <= 100; i++) { 
    cout << "loop count: " << i << endl; 
    readLine(0,0,80); 
    } 
    system("pause"); 
} 

輸出:

loop count: 0 
loop count: 1 
loop count: 2 
loop count: 3 
// [...] 
loop count: 63 
loop count: 64 

This application has requested the Runtime to terminate it in an unusual way. 
Please contact the application's support team for more information. 

(第一個文檔片斷沒有產生任何錯誤的所有)。

+1

你沒做的一件事是'''''''''''''''''''' – chris 2012-07-21 18:21:57

+1

您是否考慮檢查ReadConsoleOutputCharacterW和GetLastError的返回碼? – 2012-07-21 18:24:49

+0

@chris:如何刪除函數中的變量,因爲我必須返回它,而return是函數中執行的最後一個命令? – rsk82 2012-07-21 18:28:29

回答

1

這可能只是「一個一個」。您正在爲「Len」字符分配空間,您正在閱讀「Len」字符,但在最後加上了\ 0。

改變你的新分配Len + 1,你可能會很好。

1

dwChars應該傳遞給ReadConsoleOutputCharacterW作爲dwChars -1。 您正在覆蓋數組的末尾。