简体   繁体   English

尝试从bmp文件中提取RGB分量时,为什么我的代码段出错?

[英]Why is my code seg faulting when trying to extract the RGB components from a bmp file?

I am trying to extract the RGB components from a bmp file but I am getting a seg fault when it gets to Data[i][j].Blue . 我试图从bmp文件中提取RGB分量,但是当它到达Data[i][j].Blue时遇到段错误。 I try printing out the hex of the three colors and it prints them out good but then it prints out that all RGB components are 0xFF and then it seg faults when it gets to the blue. 我尝试打印出三种颜色的十六进制,并很好地打印出它们,但随后打印出,所有RGB分量均为0xFF,然后当它变成蓝色时就会出现故障。 Any help I get is greatly appreciated. 我得到的任何帮助将不胜感激。

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;
}

Well for starters, your first malloc uses 首先,您的第一个malloc使用

InfoHeader->Width * sizeof(struct PIXEL *)

But then you use InfoHeader->Height when iterating over the array. 但是然后在遍历数组时使用InfoHeader-> Height。 Because of this mismatch, If InfoHeader->Width is smaller than InfoHeader->Height, it will not allocate enough memory to perform the iteration, and it will SEGFAULT. 由于此不匹配,如果InfoHeader-> Width小于InfoHeader-> Height,则它将不会分配足够的内存来执行迭代,并且将执行SEGFAULT。

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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM