无法找到简单的内存泄漏
Unable to find simple memory leak
有没有人能帮我找到这里发生的内存泄漏?我只是试图使用我设计的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();
}
我不能在那里发现内存泄漏,但是程序在内存方面相当浪费:
-
加载时,它将整个文件加载到内存中,然后构建矩阵。在加载结束时,文件和矩阵都在内存中。如果格式允许,它可以尝试迭代加载文件(例如逐行加载)。
-
图像矩阵存储格式是数组的数组的数组。由于每个维度上的数组是单独分配的,并且每个分配的数组都有一定数量的内存(通常为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]
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏