Hidden Danger of static link to CRT (libcmt. Lib)

Source: Internet
Author: User

From: http://www.codeproject.com/Articles/22642/What-Every-Computer-Programmer-Should-Know-About-W

 

When the CRT/C ++ library is linked statically, then all its code is embedded into the resulting executable image. the problem is that internal CRT objects cannot be shared with other CRT instances. the memory allocated in one instance of CRT must be freed in the same instance, the file opened on one instance of CRT must be operated and closed by functions from the same instance, etc. it happens because the CRT tracks the acquired resources internally. any attempt to free a memory chunk or read from a fileFILE*That came from another CRT instance will lead to cancel uption of the internal CRT state and most likely to crash.

That's why linking CRT statically obligates a developer of a module to provide additional functions to release allocated resources and a user of a module to remember to call these functions in order to prevent resource leaks. no STL containers or C ++ objects that use allocations internally can be shared between SS modules that link to the CRT statically. the following dimo-strates the usage of a memory buffer allocated via a callmalloc.

Digoal #2: Using memory allocatedmallocFrom different modules

In the above digoal, Module 1 is linked to the CRT statically (libcmt. lib), while modules 2 and 3 are linked to the CRT dynamically (msvcrt. DLL ). modules 2 and 3 can pass CRT owned objects between them freely. for example, a memory chunk allocatedmallocIn Module 3 can be freed in Module 2free. It is because bothmallocAndfreeCallwill end up in the same instance of CRT.

On the other hand, Module 1 cannot let other modules to free its resources. everything allocated in Module 1 must be freed by Module 1. it is because only Module 1 has access to the statically linked instance of the CRT. in the above sample, Module 2 must remember to call a function from Module 1 in order to properly release the acquired memory.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.