zeroing out memory

后端 未结 12 2023
無奈伤痛
無奈伤痛 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:07

    This post has been heavily edited to make it correct. Many thanks to Tyler McHenery for pointing out what I missed.

    char buffer[1024] = {0};
    

    Will set the first char in the buffer to null, and the compiler will then expand all non-initialized chars to 0 too. In such a case it seems that the differences between the two techniques boil down to whether the compiler generates more optimized code for array initialization or whether memset is optimized faster than the generated compiled code.

    Previously I stated:

    char buffer[1024] = {0};

    Will set the first char in the buffer to null. That technique is commonly used for null terminated strings, as all data past the first null is ignored by subsequent (non-buggy) functions that handle null terminated strings.

    Which is not quite true. Sorry for the miscommunication, and thanks again for the corrections.

提交回复
热议问题