本文介绍了为什么写入标准输出时 WriteFile 会崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个使用 WinAPI 的 WriteFile(在 Microsoft Visual C++ 2008 Express 中编译)的Hello world"程序:

Here's a "Hello world" program that uses WinAPI's WriteFile (compiled in Microsoft Visual C++ 2008 Express):

int _tmain(int argc, _TCHAR* argv[])
{
    wchar_t str[] = L"Hello world";

    HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
    if(out && out!=INVALID_HANDLE_VALUE)
    {
        WriteFile(out, str, sizeof(str), NULL, NULL);
        CloseHandle(out);
    }

    return 0;
}

如果在控制台窗口中执行,它会愉快地迎接世界.但是,如果您尝试重定向其标准输出,如

If executed in a console window, it happily greets the world. If you try to redirect its standard output, however, as in

hello.exe > output.txt

程序在 WriteFile 中崩溃(NULL 指针异常).尽管如此,output.txt 仍然存在并包含完整的正确输出.

the program crashes in WriteFile (NULL pointer exception). Nonetheless, output.txt exists and contains the correct output in its entirety.

崩溃时的调用栈:

KernelBase.dll!_WriteFile@20()  + 0x75 bytes
kernel32.dll!_WriteFileImplementation@20()  + 0x4e bytes
srgprc2.exe!wmain(int argc=1, wchar_t * * argv=0x00483d88)  Line 15 + 0x16 bytes    C++

消息:srgprc2.exe 中 0x75ce85ea (KernelBase.dll) 处的未处理异常:0xC0000005:访问冲突写入位置 0x00000000."

The message: "Unhandled exception at 0x75ce85ea (KernelBase.dll) in srgprc2.exe: 0xC0000005: Access violation writing location 0x00000000."

这里发生了什么?谢谢!

What's going on here? Thanks!

推荐答案

WriteFile的第四个参数不是可选的.您传递的是 NULL,这是不允许的.

The fourth parameter to WriteFile is not optional. You are passing NULL, which is not allowed.

这篇关于为什么写入标准输出时 WriteFile 会崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-18 11:43