Почему мой код неисправен при попытке извлечь компоненты RGB из файла bmp? - PullRequest
0 голосов
/ 15 апреля 2019

Я пытаюсь извлечь компоненты RGB из файла bmp, но у меня возникает ошибка seg, когда он достигает Data[i][j].Blue.Я пытаюсь распечатать гекс из трех цветов, и он распечатывает их хорошо, но затем он печатает, что все компоненты 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;
}

Ответы [ 2 ]

1 голос
/ 15 апреля 2019

Хорошо для начала, ваш первый malloc использует

InfoHeader->Width * sizeof(struct PIXEL *)

Но тогда вы используете InfoHeader-> Height при итерации по массиву. Из-за этого несоответствия, если InfoHeader-> Width меньше, чем InfoHeader-> Height, он не выделит достаточно памяти для выполнения итерации и будет SEGFAULT.

0 голосов
/ 15 апреля 2019
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));
}
...