title: freopen_s("conout$") and fclose
body: <p>Visual C++ is reporting that an invalid parameter was passed to <code>fclose</code>, that parameter being the <code>FILE*</code> returned by freopen_s:</p>
  
  <pre><code>#include &lt;WinSock2.h&gt;
  #include &lt;iostream&gt;
  
  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(&amp;pCout, "conout$", "w", stdout); //returns 0
  
      fclose(pCout);
  
  #ifdef _DEBUG
      system("pause");
  #endif
  
      FreeConsole();
  
      return 0;
  }
  </code></pre>
  
  <p>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?</p>