当ReadConsoleOutputCharacterW返回的字符串具有某个特定长度时,wcslen将静默退出

时间:2012-07-22 22:39:07

标签: c++ winapi console wchar-t

编译器:http://sourceforge.net/projects/mingwbuilds/files/

#include <iostream>
#include <string.h>
#include <windows.h>
using namespace std;

  const wchar_t* readConsole(int chars_to_read) {
    wchar_t* wcharFromConsole = new wchar_t[chars_to_read+1];
    COORD pos = {0,0};
    DWORD dwChars;
    if (!ReadConsoleOutputCharacterW(
      GetStdHandle(STD_OUTPUT_HANDLE),
      wcharFromConsole,  // Buffer where store symbols
      chars_to_read,     // number of chars to read
      pos,    // Read from row=8, column=6
      &dwChars // How many symbols stored
    ))
    {
      printf("ReadConsoleOutputCharacterW failed %d\n", GetLastError());
      abort();
    }
    wcharFromConsole [dwChars] = L'\0'; // Terminate, so string functions can be used
    wstring ws = wcharFromConsole;
    return ws.c_str();
  }

int main() {
  for (int i = 1; i<=0x3000; i++) {
    printf("wcslen: %X \n",wcslen(readConsole(i)));
  }
  system("pause");
}

此循环在0x1FF1结束,不调用暂停。删除wstring似乎可以解决这个问题。但是我在这里需要它来修改像空白等函数。这里没有多大关系,但为什么调用wstring会导致这个问题呢?程序退出时没有错误消息。

更新了代码,现在循环退出0x2BBF

#include <iostream>
#include <string.h>
#include <windows.h>
using namespace std;

  const wchar_t* readConsole(int chars_to_read) {
    wchar_t* wcharFromConsole = new wchar_t[chars_to_read+1];
    COORD pos = {0,0};
    DWORD dwChars;
    if (!ReadConsoleOutputCharacterW(
      GetStdHandle(STD_OUTPUT_HANDLE),
      wcharFromConsole,  // Buffer where store symbols
      chars_to_read,     // number of chars to read
      pos,    // Read from row=8, column=6
      &dwChars // How many symbols stored
    ))
    {
      printf("ReadConsoleOutputCharacterW failed %d\n", GetLastError());
      abort();
    }
    wcharFromConsole [dwChars] = L'\0'; // Terminate, so string functions can be used
    wstring ws = wcharFromConsole;
    delete [] wcharFromConsole;
    const wchar_t* wc = ws.c_str();
    return wc;
  }

int main() {
  for (int i = 1; i<=0x3000; i++) {
    printf("wcslen: %X \n",wcslen(readConsole(i)));
  }
  system("pause");
}

1 个答案:

答案 0 :(得分:2)

哎哟。

wstring ws = wcharFromConsole;
return ws.c_str();

基本上,你在这里返回一个死指针。该字符串将在返回时被销毁,因此到达调用者的指针将无效。

编辑:你也在泄漏内存,因为“新”永远不会被删除。但这通常不会引起明显的问题,只会增加程序的内存使用量。