zeroing out memory

后端 未结 12 2020
無奈伤痛
無奈伤痛 2021-01-31 09:52

gcc 4.4.4 C89

I am just wondering what most C programmers do when they want to zero out memory.

For example, I have a buffer of 1024 bytes. Sometimes I do this:<

12条回答
  •  一整个雨季
    2021-01-31 10:23

    In this particular case, there's not much difference. I prefer = { 0 } over memset because memset is more error-prone:

    • It provides an opportunity to get the bounds wrong.
    • It provides an opportunity to mix up the arguments to memset (e.g. memset(buf, sizeof buf, 0) instead of memset(buf, 0, sizeof buf).

    In general, = { 0 } is better for initializing structs too. It effectively initializes all members as if you had written = 0 to initialize each. This means that pointer members are guaranteed to be initialized to the null pointer (which might not be all-bits-zero, and all-bits-zero is what you'd get if you had used memset).

    On the other hand, = { 0 } can leave padding bits in a struct as garbage, so it might not be appropriate if you plan to use memcmp to compare them later.

提交回复
热议问题