#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)
}
Possible Duplicate: http://stackoverflow.com/questions/1568042/optimal-way-to-free-a-malloced-2d-array-in-c
Though above link could not solve my problems.
ppColors = (COLORMAP**)malloc((pHeader -> height ) * sizeof(COLORMAP));
to
ppColors = (COLORMAP**)malloc((pHeader -> height + 6 ) * sizeof(COLORMAP));
Then this problem disappears.
I am damn sure I am going wrong somewhere. I do not expect someone to correct my code and I just run it. Just hints would do.
I can see a couple of problems:
ppColors
is an array of pointers. Each element in the array is a COLORMAP*
so you need to calculate the size to be malloced using numElements * sizeof(COLORMAP*)
. COLORMAP
is just 3 chars so its likely that sizeof(COLORMAP*)
> sizeof(COLORMAP)
. Your current allocation will be too small so you'll end up writing beyond the end of the array; this has undefined effects but is likely to crash.