marc marc - 1 year ago 75
C++ Question

Dynamic allocation leaks memory?

bool CPythonNonPlayer::LoadNonPlayerData(const char *c_szFileName)
DWORD dwElements;

TMobTable *pTable = (TMobTable *) zObj.GetBuffer();

for(DWORD i = 0; i < dwElements; ++i, ++pTable)
TMobTable *pNonPlayerData = new TMobTable;
memcpy(pNonPlayerData, pTable, sizeof(TMobTable));
m_NonPlayerDataMap.insert(TNonPlayerDataMap::value_type(pNonPlayerData->dwVnum, pNonPlayerData));

return true;

My questtion what i do wrong? This leak me memory so much. After each call of this function application usage increase with 10MB. Sorry if is not enought information just reply and i add more.

Answer Source

The problem is not in this function. The problem is in the way you handle m_NonPlayerDataMap. This function transfers ownership of some objects to that map, and it's that map's responsibility to delete them when it's done with them. I'll bet it doesn't.

By the way, to avoid this kind of problem just don't do this. Don't use new unless you really need to. Instead, make the map a map of values rather than a map of pointers. If you can't figure out any way to make that happen, at least use smart pointers rather than raw pointers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download