c - 使用 fread() 将二进制文件转换为结构体时出现问题

标签 c struct binaryfiles fread

我在使用 fread() 将二进制文件转换为结构链接列表时遇到问题。

结构:

struct MdbRec {
    char name[16];
    char  msg[24];
};

相关代码:

    FILE *file;
    file = fopen( argv[1], "rb" );

    struct List db;
    initList(&db);
    struct MdbRec *data = (struct MdbRec *)malloc(sizeof(struct MdbRec));
    struct Node *last;
    while( fread( data, 40, 1, file ) )
    {
            struct MdbRec *message = (struct MdbRec *)malloc(sizeof(struct MdbRec));
            message = data;
            if( !db.head )
            {
                    last = addFront( &db, message );
                    db.head = last;
            }
            else
                    last = addAfter( &db, last, message );
            if( fseek( file, 40, SEEK_CUR ) != 0)
                    break;
            printf("read\n");
    }
    free(data);
    removeAllNodes( &db );

addFront() 和 addAfter 是链表结构的方法,用于分配数据字段的空间。

当我使用 Valgrind 运行它时,它显示我已成功分配了 2 次内存。第一个显然是数据变量。其他 568 个字节让我很困惑。 Valgrind 说错误来自于我运行 fread() 时。

最佳答案

这是内存泄漏:

struct MdbRec *message = (struct MdbRec *)malloc(sizeof(struct MdbRec));
message = data;

as message 现在指向 data 并且不再指向刚才的 malloc()d 内存,该内存现在无法访问。我怀疑您实际上是想复制 数据消息:

*message = *data;

其他要点:

  • 使用前检查fopen()的结果。
  • 似乎没有理由不为数据使用堆栈分配的对象,这将避免不必要的动态分配管理。
  • 指定要读取的对象大小的 fread() 参数 40 很容易出错。对 struct MdbRec 的任何更改都会破坏它:请改用 sizeof(struct MdbRec)
  • 强制转换 malloc() 的返回值是不必要的,而且可能很危险(请参阅 Do I cast the result of malloc? )。

关于c - 使用 fread() 将二进制文件转换为结构体时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13001602/

相关文章:

c++ - 仅使用 C 结构并保持 OOPy?

c - 二维字符数组的 malloc 函数的段错误

c - 从输入文件中提取数据?

c - 从结构中添加或删除数据

c++ - 在 C++ 类中导致编译错误的结构

c++ - 逐字节读取二进制 istream

c - 是否可以使用霍夫曼编码来压缩二进制文件?

是否可以在其定义中取自动存储期限的变量的地址?

C结构体指针问题

c 二进制文件读取问题