'Ncurses 'new_item' function mem leak or what am i doing wrong?
I'm making a calendar in Ncurses, which means I have to dynamically allocate and free memory. The thing is that Valgrind --leak-check=full shows memory leaks in the new_item function. Here is my code. What am I doing wrong?
unordered_map<int, ITEM**>
void NcurInterface::printMenu(GUIITEMS menu, GUIITEMS win)
{
typedef ITEM *items;
// Create items
int i;
items *mitem = (ITEM**)new items[manager->getNmbMenuItems(menu) + 1];
for(i = 0; i < manager->getNmbMenuItems(menu); i++) {
mitem[i] = new_item(manager->getMenuItemsString(menu, false, i).c_str(), manager->getMenuItemsString(menu, true, i).c_str());
}
mitem[i] = ((char)NULL);
setMenuItems(menu, mitem); // Insert in map
}
void NcurInterface::freeMenuItems(GUIITEMS menu)
{
items *clr = menuItems[menu];
for(unsigned char i = 0; i < manager->getNmbMenuItems(menu) + 1; i++) {
free_item(clr[i]);
}
menuItems.erase(menu);
delete[] clr;
}
Valgrind output
1,056 (192 direct, 864 indirect) bytes in 2 blocks are definitely lost in loss record 62 of 92
at 0x4C282B8: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
by 0x5491226: new_item (in /usr/lib/x86_64-linux-gnu/libmenu.so.5.9)
by 0x4137BC: NcurInterface::printMenu(GUIITEMS, GUIITEMS) (NcurInterface.cpp:220)
by 0x413467: NcurInterface::updateMenu(GUIITEMS, GUIITEMS, GUIITEMS) (NcurInterface.cpp:185)
by 0x417810: main (NcurInterface.cpp:754)
Solution 1:[1]
The OP wrote:
Problem solved! The menu has to be unposted first, after that it can be freed and at last items can be freed. No more memory leak!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
