#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
虽然以上链接无法解决我的问题。
ppColors = (COLORMAP**)malloc((pHeader -> height ) * sizeof(COLORMAP));
到ppColors = (COLORMAP**)malloc((pHeader -> height + 6 ) * sizeof(COLORMAP));
然后这个问题消失了。
我该死的肯定我在某个地方出错了。我不希望有人改正我的代码,而只是运行它。只是提示会做。
最佳答案
我可以看到几个问题:
ppColors
是一个指针数组。数组中的每个元素都是一个COLORMAP*
,因此您需要使用numElements * sizeof(COLORMAP*)
计算要分配的大小。 COLORMAP
只是3个字符,因此sizeof(COLORMAP*)
> sizeof(COLORMAP)
很有可能。您当前的分配将太小,因此最终将超出数组末尾进行写入。这具有不确定的影响,但可能会崩溃。 关于c - 二维数组struct — malloc()和free(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14379771/