freopen_s("conout$") and fclose

NmdMystery picture NmdMystery · Nov 23, 2013 · Viewed 8.1k times · Source

Visual C++ is reporting that an invalid parameter was passed to fclose, that parameter being the FILE* returned by freopen_s:

#include <WinSock2.h>
#include <iostream>

int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) {
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(nCmdShow);

#ifdef _DEBUG
    AllocConsole();
#else
    AttachConsole(ATTACH_PARENT_PROCESS);
#endif

    FILE* pCout;
    freopen_s(&pCout, "conout$", "w", stdout); //returns 0

    fclose(pCout);

#ifdef _DEBUG
    system("pause");
#endif

    FreeConsole();

    return 0;
}

Should I not attempt to close conout$ at the end of the program? Is the exception being thrown because the file pointer is shared between processes for all console output?

Answer

James McNellis picture James McNellis · Nov 23, 2013

The call to fclose is failing because you are passing a null FILE*. The FILE* is null because the call to freopen_s fails. That call fails because the process has no console to be opened.

Your program works in debug builds because you call AllocConsole to allocate a console for your process. Your program does not work in release builds because you do not call AllocConsole; you call AttachConsole, which will fail (and have no effect) if the parent process has no console.