当ReadConsoleOutputCharacterW返回的字符串具有特定长度时,wcslen会静默退出
wcslen quits silently when string returned by the ReadConsoleOutputCharacterW has some particular length
编译器: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 %dn", GetLastError());
abort();
}
wcharFromConsole [dwChars] = L' '; // 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 %dn", GetLastError());
abort();
}
wcharFromConsole [dwChars] = L' '; // 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");
}
哎哟。
wstring ws = wcharFromConsole;
return ws.c_str();
基本上,你在这里返回了一个死指针。字符串将在返回时被销毁,因此到达调用方的指针将无效。
编辑:你也在泄露内存,因为"新"永远不会被删除。但这通常不会引起明显的问题,只会增加程序的内存使用量。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 创建LinkedList退出,返回代码为-11(SIGSEGV)
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何让LLDB在成功时退出,在失败时等待
- C++控制台应用程序阻止退出
- 程序在执行程序的其余部分之前退出
- 构造函数在退出函数时无法初始化一个参数
- 为什么异常不退出程序?
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- 退出简单while循环时出现问题
- 使用vscode调试时,GDB意外退出
- pclose() 不会给我进程退出代码
- 为什么系统函数总是在C++中返回已转移的退出状态?
- C++从另一个函数退出函数
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- C++逗号分隔的输入数组代码过早退出
- Netbeans 10:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- 为什么 C++ 中的以下结构声明会导致退出 127?
- 编译问题:在函数"_start"中:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 当ReadConsoleOutputCharacterW返回的字符串具有特定长度时,wcslen会静默退出