为什么我的代码在尝试从bmp文件中提取RGB组件时会出错?

问题描述 投票:0回答:2

我试图从bmp文件中提取RGB组件,但是当它到达Data[i][j].Blue时我遇到了一个seg错误。我尝试打印出三种颜色的十六进制并将它打印出来然后打印出所有RGB组件都是0xFF,然后当它变为蓝色时它会出现故障。我得到的任何帮助非常感谢。

int inputColors(char *filename, struct INFOHEADER *InfoHeader, struct PIXEL **Data){
    int i = 0, j = 0;
    FILE *inputFile;

    printf("The height of the picture is %d\n", InfoHeader->Height);
    printf("The width of the picture is %d\n", InfoHeader->Width);

    if((inputFile = fopen(filename, "r")) == NULL){
            printf("Unable to open .bmp file\n");
            exit(1);
    }

    //Mallocing enough space for the 2D structures of pixels (colors)
    Data = (struct PIXEL **)malloc(InfoHeader->Width * sizeof(struct PIXEL *));
    for(i = 0; i < InfoHeader->Height; i++){
            Data[i] = (struct PIXEL *)malloc(InfoHeader->Height * InfoHeader->Width * sizeof(struct PIXEL));
    }

    //This goes until after we are down with the header
    fseek(inputFile, 54, SEEK_SET);

    //Inputing the data into the malloced struct
    i = 0;
    for(i = 0; i < InfoHeader->Height; i++){
            for(j = 0; j < InfoHeader->Width; j++){
                    Data[i][j].Red = getc(inputFile);
            //      printf("The Red componet is %X\n", Data[i][j].Red);
                    Data[i][j].Green = getc(inputFile);
            //      printf("The green componet is %X\n", Data[i][j].Green);
                    Data[i][j].Blue = getc(inputFile);
            //      printf("The blue componet is %X\n", Data[i][j].Blue);
            }
    }

    fclose(inputFile);
return 0;
}
c segmentation-fault bmp
2个回答
1
投票

对于初学者来说,你的第一个malloc使用

InfoHeader->Width * sizeof(struct PIXEL *)

但是当你遍历数组时,你会使用InfoHeader-> Height。由于这种不匹配,如果InfoHeader-> Width小于InfoHeader-> Height,它将不会分配足够的内存来执行迭代,它将是SEGFAULT。


0
投票
Data = (struct PIXEL **)malloc(InfoHeader->Width * sizeof(struct PIXEL *));
//                                         ^^^^^
for(i = 0; i < InfoHeader->Height; i++){
//                         ^^^^^^
        Data[i] = (struct PIXEL *)malloc(InfoHeader->Height * InfoHeader->Width * sizeof(struct PIXEL));
}
© www.soinside.com 2019 - 2024. All rights reserved.