void Image_Input(IMG_t *img, char *filename, char *mode)
{
char mag;
int wid, hei, lum;
unsigned char *pix;
FILE *fp;
int i, j;
unsigned int el_n, wi;
char str[256];
unsigned char temp[256];
char shift;
int pos;
if ((fp = fopen(filename, mode)) == NULL)
{
printf("Input file open error\n");
exit(2);
}
//Input header
fgets(str, sizeof(str), fp);
sscanf(str, "P%d", &img->magN);
mag = img->magN;
i = 0;
while (1)
{
fgets(str, sizeof(str), fp);
if (str[0] == '#') continue;
if (i == 0)
{
sscanf(str, "%d %d", &img->width, &img->height);
if (mag == 1 || mag == 4)
{
img->luminance = 0;
break;
}
i++;
}
else if (i == 1)
{
sscanf(str, "%d", &img->luminance);
break;
}
}
wid = img->width;
hei = img->height;
lum = img->luminance;
//Check header
printf("Input header\n%d\n%d %d\n%d\n\n", mag, wid, hei, lum);
if (mag < 1 || mag>6) {
printf("magic number error\n");
exit(2);
}
if (wid <= 0 || hei <= 0) {
printf("Input width or height error\n");
exit(2);
}
if (lum < 0 || lum > 255)
{
printf("Input luminance error\n");
exit(2);
}
el_n = wid * hei;
if (mag == 3 || mag == 6) el_n *= 3;
img->pixels = (unsigned char*)malloc((el_n+3) * sizeof(unsigned char));
pix = img->pixels;
//Input pixels
switch (mag)
{
case 1:
case 2:
case 3:
for (i = 0; i < el_n; i++) fscanf(fp, "%d", &pix[i]);
break;
case 4:
for (i = 0; i < hei; i++)
{
wi = wid * i;
fread(temp, sizeof(unsigned char), (wid + 7) / 8, fp);
shift = 8;
pos = 0;
for (j = 0; j < wid; j++)
{
shift--;
pix[wi + j] = (temp[pos] >> shift) & 1;
if (shift == 0)
{
shift = 8;
pos++;
}
}
}
break;
case 5:
case 6:
fread(pix, sizeof(unsigned char), el_n, fp);
break;
default:
break;
}
printf("%d\n", pix[el_n-1]);
fclose(fp);
free(pix);
}
#pragma once
typedef struct {
char magN;
int width;
int height;
int luminance;
unsigned char *pixels;
}IMG_t;
img->pixels = (unsigned char*)malloc((el_n+3) * sizeof(unsigned char));
ここでeln+3にするとエラーが起きず、+2、+1にするとエラーになります。
エラーメッセージは
HEAP CORRUPTION DETECTED: after Normal block (#74) at 0x0353BBD8.
CRT detected that the application wrote to memory after end of heap buffer.
で、確保した領域外に書き込んでることだと思っているのですがどこではみ出しているかわかりません。
どなたかご教授くださいませorz