I posted a feedback to Microsoft at
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=449513
I'm confused with their answer of "This issue is by design. It's not that
the functions are not thread safe. The problem is that you're bypassing the
CRT initialization using WinMain. "
I was hoping some of you could might be able to elaborate better for me or
validate the bug in the connect website.
The code that reproduces this issue for me is:
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <crtdbg.h>
DWORD WINAPI freopenThread( LPVOID lpParam )
{
while (true)
{
freopen("CONOUT$", "w", stdout);
}
}
DWORD WINAPI fopenThread( LPVOID lpParam )
{
while (true)
{
FILE * f = fopen("c:\\valid.txt", "w");
if (f == stdout) // fopen should never return stdout
{
__asm { int 3 };
}
fclose(f);
}
}
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
)
{
CreateThread( NULL, 0, fopenThread, NULL, 0, NULL);
CreateThread( NULL, 0, freopenThread, NULL, 0, NULL);
while(true) { }
return 0;
}
Thanks
-Patrick
Every executable has an entry point. Typically, that entry point is neither
main() nor WinMain(), but some internal function provided by the vendor
which eventually calls one of those. Now, if you create a console
application, the entry point is mainACRTStartup(), which initialises the
CRT ("C RunTime [library]"), part of which is the stdout. Since you are not
using that, CRT init is not performed and you can't use stdout.
Uli
--
C++ FAQ: http://parashift.com/c++-faq-lite
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932
In addition to Ulrich's answer. If you use CRT functions in a
thread never ever use CreateThread. You should create new thread
with `_beginthreadex' function, so CRT is initialized properly for
the thread.
Alex