简体   繁体   中英

Why will cout.imbue(locale(“”)) cause memory leaks?

My compiler is Visual VC++ 2013. The following simplest program will cause a few memory leaks.

Why? How to fix it?

#define _CRTDBG_MAP_ALLOC

#include <stdlib.h>
#include <crtdbg.h>
#include <cstdlib>
#include <iostream>
#include <locale>

using namespace std;

int main()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);

    cout.imbue(locale("")); // If this statement is commented, then OK.
}

The debug window outputs as follows:

Detected memory leaks!
Dumping objects ->
{387} normal block at 0x004FF8C8, 12 bytes long.
 Data: <z h - C N   > 7A 00 68 00 2D 00 43 00 4E 00 00 00 
{379} normal block at 0x004FF678, 12 bytes long.
 Data: <z h - C N   > 7A 00 68 00 2D 00 43 00 4E 00 00 00 
{352} normal block at 0x004FE6E8, 12 bytes long.
 Data: <z h - C N   > 7A 00 68 00 2D 00 43 00 4E 00 00 00 
{344} normal block at 0x004FE498, 12 bytes long.
 Data: <z h - C N   > 7A 00 68 00 2D 00 43 00 4E 00 00 00 
{318} normal block at 0x004FD5C8, 12 bytes long.
 Data: <z h - C N   > 7A 00 68 00 2D 00 43 00 4E 00 00 00 
{308} normal block at 0x004F8860, 12 bytes long.
 Data: <z h - C N   > 7A 00 68 00 2D 00 43 00 4E 00 00 00 
Object dump complete.
Detected memory leaks!
Dumping objects ->
{387} normal block at 0x004FF8C8, 12 bytes long.
 Data: <z h - C N   > 7A 00 68 00 2D 00 43 00 4E 00 00 00 
{379} normal block at 0x004FF678, 12 bytes long.
 Data: <z h - C N   > 7A 00 68 00 2D 00 43 00 4E 00 00 00 
{352} normal block at 0x004FE6E8, 12 bytes long.
 Data: <z h - C N   > 7A 00 68 00 2D 00 43 00 4E 00 00 00 
{344} normal block at 0x004FE498, 12 bytes long.
 Data: <z h - C N   > 7A 00 68 00 2D 00 43 00 4E 00 00 00 
{318} normal block at 0x004FD5C8, 12 bytes long.
 Data: <z h - C N   > 7A 00 68 00 2D 00 43 00 4E 00 00 00 
{308} normal block at 0x004F8860, 12 bytes long.
 Data: <z h - C N   > 7A 00 68 00 2D 00 43 00 4E 00 00 00 
Object dump complete.
The program '[0x5B44] cpptest.exe' has exited with code 0 (0x0).

I was using std::codecvt and get a similar problem. I am not sure whether it is a same cause. Just try to provide s possible way to discover the root cause.

You can reference the example in http://www.cplusplus.com/reference/locale/codecvt/in/

It actually "use" the member of mylocale , and it seems without an r-value reference version overload. So when directly write const facet_type& myfacet = std::use_facet<facet_type>(std::locale()); may cause the same problem. .

So try

auto myloc = locale("");
cout.imbue(myloc);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM