c++ - 嵌套对象中的内存不可用

标签 c++ object memory-leaks valgrind free

我从 Valgrind 发现内存泄漏,它给出了内存错误:无效的 free()/delete/delete[]/realloc()。

==7367== Invalid free() / delete / delete[] / realloc()
==7367==    at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7367==    by 0x40077F: ItemSet::~ItemSet() (cart.cpp:33)
==7367==    by 0x40086B: ShoppingCart::~ShoppingCart() (cart.cpp:14)
==7367==    by 0x400828: main (cart.cpp:45)
==7367==  Address 0x5a1c0b0 is 0 bytes inside a block of size 40 free'd
==7367==    at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7367==    by 0x40077F: ItemSet::~ItemSet() (cart.cpp:33)
==7367==    by 0x400800: ShoppingCart::ShoppingCart() (cart.cpp:39)
==7367==    by 0x400817: main (cart.cpp:43)
==7367== 
==7367== 
==7367== HEAP SUMMARY:
==7367==     in use at exit: 40 bytes in 1 blocks
==7367==   total heap usage: 2 allocs, 2 frees, 80 bytes allocated
==7367== 
==7367== LEAK SUMMARY:
==7367==    definitely lost: 40 bytes in 1 blocks
==7367==    indirectly lost: 0 bytes in 0 blocks
==7367==      possibly lost: 0 bytes in 0 blocks
==7367==    still reachable: 0 bytes in 0 blocks
==7367==         suppressed: 0 bytes in 0 blocks
==7367== Rerun with --leak-check=full to see details of leaked memory
==7367== 
==7367== For counts of detected and suppressed errors, rerun with: -v
==7367== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

这是代码。它是我的程序的简化版本,但它仍然存在我遇到的问题。

#include <cstdlib>

class ItemSet {
    private:
        int* items;

    public:
        ItemSet();
        virtual ~ItemSet();

        // ItemSet Methods...
};

class ShoppingCart {
    private:
        ItemSet items_in_cart;
    public:
        ShoppingCart();

        // ShoppingCart methods...
};

ItemSet::ItemSet() {
    // Constructor
    int max_num_of_items = 10;
    items = (int*)calloc(sizeof(int), max_num_of_items);
}

ItemSet::~ItemSet() {
    // Destructor
    if (NULL != items) {
        // Frees the dynamically allocated register files
        free(items);
    }
}

ShoppingCart::ShoppingCart() {
    // Constructor
    items_in_cart = ItemSet();
}

int main() {
    ShoppingCart cart = ShoppingCart();

    return 0;
}

最佳答案

ShoppingCart::ShoppingCart() {
    // Constructor
    items_in_cart = ItemSet();
}

最后一行不可能起作用。分配后,我们有两个具有相同 items 值的 ItemSet 对象 - 在右侧创建的临时对象和 items_in_cart。当第二个被摧毁时,你将获得双重释放。

使用明智的方法来收集对象,例如 std::liststd::vectorstd::array 。否则,请按照 rule of 3 操作,规则of 5 ,或为零。

关于c++ - 嵌套对象中的内存不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35357989/

相关文章:

c++ - 使用新位图修改 CreateToolbarEx 函数时出现内存分配问题

javascript - 在 JavaScript 中有效地计算对象的键/属性的数量

memory-leaks - Instruments 堆栈跟踪中缺少方法调用

ios - 这个关闭会导致内存泄漏吗?

C++:防止多个函数同时执行

java - 创建 Java native 接口(interface)的问题

javascript - 对象数组,在 JavaScript 中具有单独的属性

Javascript 特异性(仅响应单击的项目)

ios - 对象的潜在泄漏-调用函数“ABMultiValueCopyValueAtIndex”将返回保留计数为+1的Core Foundation对象

c++ - 在不带参数的函数声明中指定使用 void 是否解决了最令人烦恼的解析问题?