Wednesday, December 29, 2004

Weird crashing problems with Windows C/C++ multi-threading applications

Have you ever wondered why your C/C++ multi-threaded Windows applications crash mysteriously and randomly with memory corruption errors, even though you are absolutely sure that all your shared resources have been protected by some sorts of Semaphores or CriticalSection objects?

Maybe it's because you forgot to turn a specific compiler option.

There is a compiler option flag called "Runtime Library" which needs to be turned to either "Multi-threaded Debug (/MTd)" or "Multi-threaded (/MT)" when you write multi-threaded applications. By default, Microsoft Visual Studio .Net 2003 set this option to "Single-threaded Debug (/MLd)".

If you write multi-threaded applications with "Single-threaded Debug" option, numerous common Win32 or C++ runtime routines will fail with memory corruption errors. This is because the linker uses LIBCD.lib to resolve external symbols when you are in "Single-threaded Debug" mode; that library is not designed to be thread-safe. "Mutli-threaded Debug" mode uses LIBCMTD.lib, which is designed to be thread-safe.

In Microsoft Visual Studio .Net 2003, you can change this option by the following steps:
1. Right-click on your project file and click "Properties".
2. Expand "C/C++" folder.
3. Click "Code-generation".
4. Under "Runtime Library" on the right, select "Multi-threaded Debug (/MTd)" or "Multi-threaded (/MT)".
5. Note that you must select "Multi-threaded Debug (/MTd)" when your configuration is "Debug", and you must select "Multi-threaded (/MT)" when your configuration is "Release". Otherwise you'll run into various linker errors.

No comments: