gpt4 book ai didi

c - 未初始化的结构成员 : best practice

转载 作者:太空宇宙 更新时间:2023-11-04 05:13:40 25 4
gpt4 key购买 nike

在我的代码中,我有一个这样的结构:

struct fileinfo {
/* ... */
bool hashed;
char hash[20];
}

当且仅当设置了hashed 时,每个处理struct fileinfo 的函数才读取hash 的值。我的程序将其中几个 struct fileinfo 写入一个临时文件以供稍后使用:

struct fileinfo info;

/* ... */

info.hashed = false;

/* ... */

if (fwrite(&info,sizeof info,1,m->info_file) != 1) {
perror("Error writing to temporary file");
return 1;
}

Valgrind 现在提示我将未初始化的内存传递给系统调用 write。处理这种情况的最佳做法是什么?预先将成员 hash 简单地 memset 到零字节是最好的主意吗?

最佳答案

我通常只是在使用前memset整个东西。

memset( &info, 0, sizeof(info) );

关于c - 未初始化的结构成员 : best practice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18344080/

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