memset() or value initialization to zero out a struct?

后端 未结 8 2171
你的背包
你的背包 2020-11-27 10:29

In Win32 API programming it\'s typical to use C structs with multiple fields. Usually only a couple of them have meaningful values and all others have to be zer

8条回答
  •  攒了一身酷
    2020-11-27 11:15

    If there are lots of pointer members and you are likely to add more in the future, it can help to use memset. Combined with appropriate assert(struct->member) calls you can avoid random crashes from trying to deference a bad pointer that you forgot to initialize. But if you're not as forgetful as me, then member-initialization is probably the best!

    However, if your struct is being used as part of a public API, you should get client code to use memset as a requirement. This helps with future proofing, because you can add new members and the client code will automatically NULL them out in the memset call, rather than leaving them in a (possibly dangerous) uninitialized state. This is what you do when working with socket structures for example.

提交回复
热议问题