提问者:小点点

我在构造函数中检测到valgrid的内存问题。我怎么解决这个?


目前我正在学习类和构造函数。我修改了下面的代码。当我用valgrid运行代码时,它会给出存在内存问题的消息。我不知道这些是从哪来的。

#include <iostream>

class Container
{
...

public:
    // constructors
    Container() {
        length = 0;
        data = nullptr;
        print("default constructor");}

    Container(int len){
        int lenght = len;
        data = new double[lenght];
    }

    Container(std::initializer_list<double> il): Container(il.size())
    {
        std::copy(il.begin(), il.end(), data);
    }

   

    // destructor

    // operators
    void print(const std::string& info) const
    {
        // print the address of this instance, the attributes `length` and
        // `data` and the `info` string
        std::cout << "  " << this << " " << length << " " << data << "  "
            << info << std::endl;
    }

private:
    int length;
    double* data;
};

int main()
{
    Container x = {1,2,3,4};
    std::cout << "x has address " << &x << std::endl;
    
    return 0;
}

这是我从ValGrid得到的输出:

Valgrind detected memory issues:
==21== Memcheck, a memory error detector
==21== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==21== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==21== Command: ./temp_student_code
==21== 
x has address 0x1fff000ca0
==21== 
==21== HEAP SUMMARY:
==21==     in use at exit: 74,035 bytes in 10 blocks
==21==   total heap usage: 11 allocs, 1 frees, 74,091 bytes allocated
==21== 
==21== 32 bytes in 1 blocks are definitely lost in loss record 1 of 6
==21==    at 0x489F344: operator new[](unsigned long) (vg_replace_malloc.c:433)
==21==    by 0x109379: Container::Container(int) (student_code.cpp:20)
==21==    by 0x1093D8: Container::Container(std::initializer_list<double>) (student_code.cpp:23)
==21==    by 0x109285: main (student_code.cpp:49)
==21== 
==21== LEAK SUMMARY:
==21==    definitely lost: 32 bytes in 1 blocks
==21==    indirectly lost: 0 bytes in 0 blocks
==21==      possibly lost: 0 bytes in 0 blocks
==21==    still reachable: 74,003 bytes in 9 blocks
==21==         suppressed: 0 bytes in 0 blocks

我自己也搞不清楚哪里出了问题。我可以得到一些关于如何解决内存问题的建议吗?


共1个答案

匿名用户

>

  • 您缺少释放通过new手动分配的内存所需的析构函数。

    您正在将长度保存在局部变量int lenght=len;中,您可能希望将其保存在类成员length中。

    即。一个最小的例子是:

    #include <iostream>
    
    class Container
    {
    public:
        // constructors
        Container() = default() // no allocation!
        Container(int len) : length(len) {
            data = new double[len];
        }
    
        // destructor
        ~Container() {
          if (data != nullptr) {
            // need to release memory!
            delete[] data;
        }
    
        // Other stuff ...
    
    private:
        int length = 0;
        double* data = nullptr;
    };