我在使用 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/