Can someone please help me find the memory leak which is occurring here? I am just attempting to load a 1600×960 24bit RAW image (46,08,000 bytes) into memory using an Image class I designed. In memory its taking 30MB, as I see in task manager..
Even after the destructor is called (going out of scope) it still takes up 2M. Please help!
#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();
}
I can not spot a memory leak there, but the program is rather wasteful in terms of memory:
When loading, it loads the entire file into memory and then construct the matrix. At the end of loading it has both the file and the matrix in memory. It could try loading the file iteratively (e.g. line by line) if the format allows.
The image matrix storage format is an array of arrays of arrays. Since arrays on each dimension allocated separately and for each allocated array there is some amount of memory (8-16 bytes normally) used for memory allocator internals, such a way of storing the matrix wastes a lot of memory. Try using a plain
std::vector<>, e.g. ideally: