Why does WriteFile crash when writing to the standard output?

孤者浪人 提交于 2019-12-18 07:36:47

问题


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

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

The call stack on crash:

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++

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

What's going on here? Thanks!


回答1:


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




回答2:


4th parameter (which tells us how much bytes were actually written) is expecting pointer to DWORD value (a.k.a unsigned int) when you pass NULL to that parameter it attempts to write DWORD to null pointer which causes exception, not only it is mandatory to pass pointer to that argument but also you should always check its value after write because there is probability although slim that WriteFile will write less data than you provided.



来源:https://stackoverflow.com/questions/8195608/why-does-writefile-crash-when-writing-to-the-standard-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!