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

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

处理astruct fileinfo的每个函数仅当且仅当设置了hash时才读取hashed的值。我的程序将其中的几个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。处理此类案件的最佳做法是什么?预先将成员memset简单地hash到零字节是不是最好的主意?

最佳答案

我通常只是在使用前把整件事都做完。

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

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

10-13 08:19