WriteConsoleOutputCharacter 使控制台应用程序崩溃 [英] WriteConsoleOutputCharacter crashing the Console Application
问题描述
当尝试使用 WriteConsoleOutputCharacter 函数时,应用程序崩溃.
When trying to use the WriteConsoleOutputCharacter function, the application crashes.
COORD pos;
pos.X = 0;
pos.Y = 0;
HANDLE buffer = GetStdHandle(STD_OUTPUT_HANDLE);
LPDWORD written;
char* str = "s";
WriteConsoleOutputCharacter(buffer, str, strlen(str), pos, written);
但 WriteConsole 函数正常工作:
but the WriteConsole function works correctly:
WriteConsole(buffer1,str,strlen(str),written,NULL);
我没有收到任何错误,但 Windows应用程序停止响应"通知,而且我无法使用调试器,因为我使用的 IDE(Dev C++ 5.11)有一个损坏的.
I'm not getting any error but the Windows "application stopped responding" notification, and i can't use a debugger since the IDE I'm using (Dev C++ 5.11) has a broken one.
推荐答案
变量写的
指向在哪里?该函数将取消引用该参数以设置写入的字符数.如果变量没有初始化,它将有一个不确定值,并且看起来指向一个随机位置,导致在取消引用时未定义行为.
Where is the variable written
pointing? The function will dereference that argument to set the number of characters written. If the variable is not initialized it will have an indeterminate value, and be seemingly pointing at a random location, leading to undefined behavior when being dereferenced.
改为使用普通的 DWORD
并使用地址运算符 &
:
Instead use a plain DWORD
and use the address-of operator &
:
DWORD written;
WriteConsoleOutputCharacter(buffer, str, strlen(str), pos, &written);
// ^
// Note the address-of operator here
或者如果您对写入的字符数不感兴趣,请改为传递 nullptr
.
Or if you're not interested in how many characters were written, pass nullptr
instead.
这篇关于WriteConsoleOutputCharacter 使控制台应用程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!