【问题标题】:WriteConsoleOutputCharacter crashing the Console ApplicationWriteConsoleOutputCharacter 使控制台应用程序崩溃
【发布时间】:2017-07-28 21:51:04
【问题描述】:

尝试使用WriteConsoleOutputCharacter 函数时,应用程序崩溃。

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 函数可以正常工作:

WriteConsole(buffer1,str,strlen(str),written,NULL);

我没有收到任何错误,但 Windows“应用程序停止响应”通知,我无法使用调试器,因为我使用的 IDE (Dev C++ 5.11) 有一个损坏的。

【问题讨论】:

  • LPDWORD written - 当然是崩溃。你需要使用DWORD writtenWriteConsoleOutputCharacter(buffer, str, strlen(str), pos, &written);

标签: c++ windows winapi output console-application


【解决方案1】:

变量written指向在哪里?该函数将取消引用该参数以设置写入的字符数。如果变量未初始化,它将有一个 indeterminate 值,并且看似指向一个随机位置,在被取消引用时会导致 未定义的行为

改为使用普通的DWORD 并使用地址运算符&

DWORD written;

WriteConsoleOutputCharacter(buffer, str, strlen(str), pos, &written);
//                                                         ^
//                         Note the address-of operator here

或者,如果您对写入了多少个字符不感兴趣,请改为传递 nullptr

【讨论】:

  • 嗯,DWORD和LPDWORD有什么区别?指向 LPDWORD 变量导致此错误 - 无法将 'DWORD** {aka long unsigned int**}' 转换为 'LPDWORD {aka long unsigned int*}' -。相反,指向 DWORD 变量可以正常工作。谢谢!
  • @SimoneBondi LPDWORDlong * 的宏。所以如果你做LPDWORD written;,你基本上就是在做long *written;P 代表 指针
猜你喜欢
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-25
  • 1970-01-01
相关资源
最近更新 更多