gpt4 book ai didi

c - 将 C bmp 读入内存时出现问题

转载 作者:行者123 更新时间:2023-11-30 20:24:25 25 4
gpt4 key购买 nike

我正在尝试将 .bmp header 读入内存。当我运行程序时,我得到了一个核心转储。

BMP_Image *Read_BMP_Header(FILE* fptr) {

fseek(fptr, 0, SEEK_SET);
BMP_Image *bmp_image = NULL;

bmp_image = malloc(sizeof(BMP_Header));
fread(&bmp_image->header, sizeof(BMP_Header), 1, fptr);
return bmp_image;
}

读取时的错误。

header 结构为:

typedef struct _BMP_Header
{
uint16_t type; // Magic identifier
uint32_t size; // File size in bytes
uint16_t reserved1; // Not used
uint16_t reserved2; // Not used
uint32_t offset; // Offset to image data in bytes from beginning of file (54 bytes)
uint32_t DIB_header_size; // DIB Header size in bytes (40 bytes)
int32_t width; // Width of the image
int32_t height; // Height of image
uint16_t planes; // Number of color planes
uint16_t bits; // Bits per pixel
uint32_t compression; // Compression type
uint32_t imagesize; // Image size in bytes
int32_t xresolution; // Pixels per meter
int32_t yresolution; // Pixels per meter
uint32_t ncolours; // Number of colors
uint32_t importantcolours; // Important colors
} BMP_Header;

图像结构为:

typedef struct _BMP_Image {
BMP_Header header;
unsigned char *data;
} BMP_Image;

最佳答案

你的主要问题是

bmp_image = malloc(sizeof(BMP_Header));

应该是

bmp_image = malloc(sizeof(BMP_Image));

这样就可以避免这种错误

bmp_image = malloc(sizeof(*bmp_image));

失败的原因可能有很多,但这肯定是错误的,因为您正在为 BMP_Header * 分配空间,但用 BMP_Image * 指向它,这是不同尺寸的结构。取消引用指针将成为未定义的行为,因为您无法保证给定的行为。

关于c - 将 C bmp 读入内存时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33558052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com