简体   繁体   中英

Leaking Memory In C++ With boost::ptr_vector

I been working in a project, but recently I check if my program has some leaking and the results is that it's leaking and a lot.

I use _CrtDumpMemoryLeaks(); to receive all the messages of leaking and I check that most of them are related with boost, I know that it must be my problem, but I can't understand why it's leaking.

In the debug output shows me these lines:

Dumping objects ->
{673} normal block at 0x00E075E0, 8 bytes long.
 Data: <H   @e  > 48 92 E0 00 40 65 E0 00 
{671} normal block at 0x00E065C0, 8 bytes long.
 Data: <@e      > 40 65 E0 00 00 00 00 00 
{669} normal block at 0x00E06540, 68 bytes long.
 Data: < e  mountains.pn> C0 65 E0 00 6D 6F 75 6E 74 61 69 6E 73 2E 70 6E 
{665} normal block at 0x00E063B0, 8 bytes long.
 Data: <H       > 48 92 E0 00 00 00 00 00 
{663} normal block at 0x00E09248, 68 bytes long.
 Data: < c  nubes.png   > B0 63 E0 00 6E 75 62 65 73 2E 70 6E 67 00 CD CD 

Which leads me to believe that the problem is where I use those strings, and the first call with those are in these lines:

tutorialLevel->addLayerToList("nubes.png", 1600.f, 720.f, 1.0f, 0.0f, 0.1f, true);
tutorialLevel->addLayerToList("mountains.png", 1600.f, 720.f, speedXVectorPanda.at(0), 0.0f, 0.5f, false);

And the actual function addLayerToList is the next:

void Level::addLayerToList(std::string name, GLfloat widthLayer, GLfloat heightLayer, GLfloat velX, GLfloat velY, 
                GLfloat constantX, bool hasRepetition)
{
    layersList.push_back( new Layer(name, widthLayer, heightLayer, velX, velY, constantX, hasRepetition) );
}

And layersList is define like this:

boost::ptr_vector< Layer > layersList;

Maybe, I misunderstood how the ownership of pointers work in Boost, but in the examples I recently check, this is a correct way to pass ownership of the object to the ptr_vector , am I wrong?

And my other question is, if it's necessary release the pointers for the vector, or it's better leave the auto_ptr do his work?

Thanks for the help.

Depending on where you placed it but in almost all cases, _CrtDumpMemoryLeaks will not show you the truth when using STL/BOOST smart pointers. It will see the usage of new within the STL as a memory leak.

I'm sorry, I found out what was the problem and it is really stupid, really doesn't exist another word for that.

I forgot that the class that handles dinamically Level it wasn't allocated with new, so until the main function finishes, it wasn't clean all the data, so my solution was create a method for cleanUp the class before go out of scope, so in this way all the pointer we're correctly deallocated.

Thanks to everyone for the help.

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