多次调用函数会导致程序退出,并出现一个神秘的错误
function called multiple times causes program to exit with enigmatic error
我将问题隔离为以下代码:
#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' '; // 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' '; // 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.
(第一次剪切根本没有产生任何错误。)
这可能只是"一个接一个"。你在为"Len"字符分配空间,你在读"Len"字符,但你在末尾加了一个\0。
把你的新衣服换成Len+1,你可能会没事的。
dwChars
应作为dwChars -1
传递给ReadConsoleOutputCharacterW
。您正在覆盖数组的末尾。
相关文章:
- 试图修复一个错误,该错误不会让我开始编程其余部分
- MSVC 无法根据模板参数进行数学运算,这是一个错误吗?
- 我正在尝试一个傻瓜 C++ 练习,我遇到了一个错误,说类 'GraduateStudent' 没有任何名为 'advisor' 的字段
- 零四元数和任何向量都不为零的特征积,这是一个错误吗?
- 处理程序的模块列表中有一个错误的模块"WebSocketModule"
- 在 C++ 中使用 "transform" 会给出一个错误,指出这未在作用域中声明
- 在Cython中使用C库时,我遇到了一个错误
- 我需要帮助创建一个评分系统,但它一直给我一个错误,注释掉的整数是给我带来麻烦的部分
- 我试图用c++编写递归fibonacci序列,但当我编译时,我遇到了一个错误
- 从system()调用G++会返回一个错误
- 在Visual Studio中,与std::async一起使用时不调用"thread_local"变量"析构函数,这是一个错误吗?
- 我收到一个错误无效的操作数,类型为 const char [42] 和二进制"运算符+"的双倍数
- 使用声明:GCC 和 Clang 的另一个错误?
- 全球免费给出一个错误.调试器不解释
- 相对于继承的构造函数,gcc 编译器是否还有一个错误?
- 为什么直接传递"this"指针来存档是一个错误,而另一个相同类型的指针是可以的?
- 为什么第三板有一个错误
- 如何编写一个错误结构,该结构可以包含不同的强键枚举作为错误代码
- 使用本地类型声明的G lambda被使用但从未定义 - 确实是一个错误
- 我需要在 Android Studio 中构建 NDK. 但它返回一个错误