c - 调用 fread 后奇怪的 printf 行为

标签 c bitmap dos bmp watcom

我正在尝试设计一个将位图图像加载到内存中并最终显示它的函数。 我正在使用目标设置为 DOS 的 Watcom 16 位 C 编译器编译代码。我在 DOSBox 中运行该程序。 代码如下:

#ifndef __BITMAP_H__
#define __BITMAP_H__

#include <stdio.h>
#include <stdlib.h>

typedef struct DIB
{
    int header_size;
    int px_width;
    int px_height;
}DIB_t;

DIB_t *load_bitmap(char *file_name)
{
    FILE *bmp_file;
    DIB_t *bitmap;
    char garbage[4];
    int c, file_size, pixel_offset;

    bitmap = (DIB_t*)malloc(sizeof bitmap);

    if(!bitmap)
    {
        perror("malloc()");
        return NULL;
    }

    bmp_file = fopen(file_name, "rb");

    if(!bmp_file)
    {
        perror("fopen()");
        return NULL;
    }

    c = fgetc(bmp_file);

    if(c == 'B')
    {
        c = fgetc(bmp_file);

        if(c == 'M')
        {
            fread(&file_size, 4, 1, bmp_file);
            fread(garbage, 1, 4, bmp_file);
            fread(&pixel_offset, 4, 1, bmp_file);
            fread(&bitmap->header_size, 4, 1, bmp_file);
            fread(&bitmap->px_width, 4, 1, bmp_file);
            fread(&bitmap->px_height, 4, 1, bmp_file);
            printf("BMP width: %dpx\nBMP Height: %dpx", bitmap->px_width, bitmap->px_height);
            fclose(bmp_file);
            return bitmap;
        }
    }

    fputs("File format not supported.\n", stderr);
    fclose(bmp_file);
    return NULL;
}
#endif

当你运行这个程序时它会输出:"BMP width: %dpx\n"但在换行符之后没有任何内容?? 我觉得这非常奇怪。我已经确认没有任何操作失败或设置了 errno,并且 px_height 实际上设置为它的适当值。 你们有没有遇到过这种情况?

最佳答案

你只是为这一行的指针分配了足够的空间

bitmap = (DIB_t*)malloc(sizeof(bitmap));

你真正需要的是

bitmap = (DIB_t*)malloc(sizeof(DIB_t));

此外,正如 mrbatch 指出的那样,您正在使用 16 位编译器,因此试图将 4 个字节的数据读取到 2 个字节的 int 变量中。确保您的类型的 sizeof() 与您正在阅读的内容相匹配,例如一个 long int

所以 - 一般来说 - 您通过写入比您应该的更多的数据来破坏您的堆栈和堆,并且您可以期望您的程序表现得非常奇怪:)

关于c - 调用 fread 后奇怪的 printf 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17793047/

相关文章:

shell - 如何在 diff 查看器仍然打开的情况下让cleartool diff 返回到命令行?

batch-file - 将用户切换为管理员的批处理脚本

c - 错误 : incompatible types when assigning to type 'char[20]'

c - 结构选项错误 : array type has incomplete element type

android - 圆形鱼眼畸变是顺时针旋转270度还是逆时针旋转90度才畸变?

android - 为什么我得到 Canvas : trying to use a recycled bitmap android. 图形?

unix - 如何检查文本文件的行尾以查看它是 unix 还是 dos 格式?

c - 在 STM32 上运行 TCP 服务器和 UDP 客户端

c - 如何清除 Code::blocks 中的输出屏幕?

delphi - Delphi 中透明光标显示错误颜色