无法找到简单的内存泄漏

Unable to find simple memory leak

本文关键字:内存 泄漏 简单      更新时间:2023-10-16

有没有人能帮我找到这里发生的内存泄漏?我只是试图使用我设计的image类将1600x960 24位RAW图像(46,08,000字节)加载到内存中。在内存中,它占用30MB,正如我在任务管理器中看到的。

即使在析构函数被调用(超出作用域)之后,它仍然占用2M。请帮助!

#include <cstdio>
#include <iostream>
struct pixel {
    char* color;  // to support various BPP
};
class Image
{
    private:
        pixel** image;
        int     width;
        int     height;
        int     BPP;    // bytes per pixel
        int     size;   // in bytes
    public:
        Image(std::string src, int width, int height, int BPP);
        ~Image();
        pixel** get_matrix(int col, int row, int BPP);
};
pixel** Image :: get_matrix(int col, int row, int BPP)
{
            pixel** matrix = new pixel*[row];
            for(int i=0 ; i<row ; i++)
            {
                matrix[i] = new pixel[col];
                for(int j=0 ; j<col ; j++)
                    matrix[i][j].color = new char[BPP];
            }
            return matrix;
}
Image :: Image(std::string src, int width, int height, int BPP)
{
    FILE *in;
    if( (in = fopen(src.c_str(), "rb")) == NULL )
        image = NULL;
    else
    {
        this->height = height;
        this->width  = width;
        this->BPP    = BPP;
        this->size   = width*BPP*height;
        image = get_matrix(width,height,BPP);
        char* buffer = new char[size];
        fread(buffer, sizeof(char), size, in);
        int l=0;
        for(int i=0 ; i<height ; i++)
        {
            for(int j=0 ; j<width ; j++)
            {
                for(int k=0 ; k<BPP ; k++)
                    image[i][j].color[k] = buffer[l++];
            }
        }
        delete []buffer;
        fclose(in);
    }
}
Image :: ~Image()
{
    for(int i=0 ; i<height ; i++)
    {
        for(int j=0 ; j<width ; j++)
            delete []image[i][j].color;
        delete []image[i];
    }
    delete []image;
}
int main()
{
    {
        getchar();
        Image in("x.raw", 1600, 960, 3);
        getchar();
    }
    getchar();
}

我不能在那里发现内存泄漏,但是程序在内存方面相当浪费:

  1. 加载时,它将整个文件加载到内存中,然后构建矩阵。在加载结束时,文件和矩阵都在内存中。如果格式允许,它可以尝试迭代加载文件(例如逐行加载)。

  2. 图像矩阵存储格式是数组的数组的数组。由于每个维度上的数组是单独分配的,并且每个分配的数组都有一定数量的内存(通常为8-16字节)用于内存分配器内部,因此这种存储矩阵的方式浪费了大量内存。尝试使用普通的std::vector<>,例如:

    struct RGB24 { uint8_t r, g, b; }; // one for each pixel format
    std::vector<RGB24> image(width * height); // allocate the matrix in one shot
    RGB24& pixel = image[row * width + col]; // get pixel image[row][col]