gpt4 book ai didi

c++ - 当 ReadConsoleOutputCharacterW 返回的字符串具有特定长度时 wcslen 静默退出

转载 作者:行者123 更新时间:2023-11-28 03:34:06 24 4
gpt4 key购买 nike

编译器: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 处结束并且没有调用 pause。删除 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");
}

最佳答案

哎呀。

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

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

编辑:你也在泄漏内存,因为"new"永远不会被删除。但这通常不会导致明显的问题,只会增加程序的内存使用。

关于c++ - 当 ReadConsoleOutputCharacterW 返回的字符串具有特定长度时 wcslen 静默退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11604553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com