#pragma pack(push, 1)
typedef struct
{
/*...*/
unsigned int dataoffset; //No of bytes before actual pixel data
}HEADER;
typedef struct
{
/*...*/
unsigned int width;
unsigned int height;
unsigned short bits_per_pixel; //code is written for 24 bits only and No other format is supported..
/*...*/
}INFO_HEADER;
typedef struct
{
unsigned char b;
unsigned char g;
unsigned char r;
}COLORMAP;
#pragma pack(pop)
int main()
{
// Var decl.
INFO_HEADER *pHeader = NULL;
FILE *pImage;
COLORMAP **ppColors;
/*...*/
/* File opened in read, binary mode, memory allocated for pHeader*/
fread (pHeader, sizeof(INFO_HEADER), 1, pImage);
/*Next block is actually problematic.. Posting 'as is' from my code*/
ppColors = (COLORMAP**)malloc((pHeader -> height ) * sizeof(COLORMAP));
for(i = 0 ; i < pHeader -> height ; i++)
ppColors[i] = (COLORMAP*)malloc(pHeader -> width * sizeof(COLORMAP));
fseek(pImage, pHeader -> fileheader.dataoffset, SEEK_SET);
for (i = 0 ; i < pHeader -> width ; i++)
{
for (j = 0 ; j < pHeader -> height ; j++)
{
fread(&b, sizeof(unsigned char), 1, pImage);
fread(&g, sizeof(unsigned char), 1, pImage);
fread(&r, sizeof(unsigned char), 1, pImage);
ppColors[i][j].b = b;
ppColors[i][j].g = g;
ppColors[i][j].r = r;
printf("width = %d height = %d %d:\t", i, j, cnt);
printf("%d ", (int)ppColors[i][j].b);
printf("%d ", (int)ppColors[i][j].g);
printf("%d\n", (int)ppColors[i][j].r);
cnt++;
}
}
/*And at last free()ing..*/
for(i = 0 ; i < pHeader -> height ; i++) free(ppColors[i]);
free(ppColors);
cleanup();
return(0)
}
可能重复:http ://stackoverflow.com/questions/1568042/optimal-way-to-free-a-malloced-2d-array-in-c
虽然上面的链接无法解决我的问题。
- 我的内存用完了。我对高度进行了 malloc() 处理,然后对于每个高度,宽度再次进行了 malloc() 处理。我正在尝试仅在宽度 X 高度域上工作。看来问题出在身高上。如果你改变
ppColors = (COLORMAP**)malloc((pHeader -> height ) * sizeof(COLORMAP));
至
ppColors = (COLORMAP**)malloc((pHeader -> height + 6 ) * sizeof(COLORMAP));
然后这个问题就消失了。
- 但是在 free()ing 时,我在核心转储中得到双重释放/损坏。
我该死的肯定我在某个地方出错了。我不希望有人纠正我的代码,我只是运行它。只是提示就可以了。