Why doesn't free() zero out the memory prior to releasing it?

后端 未结 14 2946
长情又很酷
长情又很酷 2020-12-15 12:17

When we free() memory in C, why is that memory not filled with zero? Is there a good way to ensure this happens as a matter of course when calling free()<

14条回答
  •  臣服心动
    2020-12-15 12:37

    If you want the memory to be set to 0 when you free it, you'll have to do it yourself before you free() it. If you try after you free() it there are no guarantees that it hasn't been allocated again. For instance you can use memset() for that.

    free() doesn't guarantee that the memory will be cleared because C doesn't guarantee that malloc() will return initialized memory. Either way you have to initialize it yourself after it's been allocated, so there's no point in clearing it when it's free()'d

提交回复
热议问题