Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

windows - Why does WriteFile crash when writing to the standard output?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...