zeroing out memory

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

    The worst that can happen? You end up (unwittingly) with a string that is not NULL terminated, or an integer that inherits whatever happened to be to the right of it after you printed to part of the buffer. Yet, unterminated strings can happen other ways, too, even if you initialized the buffer.

    Edit (from comments) The end of the world is also a remote possibility, depending on what you are doing.

    Either is undesirable. However, unless completely eschewing dynamically allocated memory, most statically allocated buffers are typically rather small, which makes memset() relatively cheap. In fact, much cheaper than most calls to calloc() for dynamic blocks, which tend to be bigger than ~2k.

    c99 contains language regarding default initialization values, I can't, however, seem to make gcc -std=c99 agree with that, using any kind of storage.

    Still, with a lot of older compilers (and compilers that aren't quite c99) still in use, I prefer to just use memset()

提交回复
热议问题