归零内存 [英] zeroing out memory

查看:133
本文介绍了归零内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GCC 4.4.4 C89

gcc 4.4.4 C89

我只是想知道,当他们想零出内存是大多数C程序员做的。

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

例如,我有1024个字节的缓冲区。有时候,我这样做:

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

char buffer[1024] = {0};

这将归零所有字节。

Which will zero all bytes.

但是,如果我宣布像这样和使用memset的?

However, should I declare it like this and use memset?

char buffer[1024];
.
.
memset(buffer, 0, sizeof(buffer));

时有你有零内存的真正原因?什么是可以由不这样做的最坏?

Is there any real reason you have to zero the memory? What is the worst that can happen by not doing it?

推荐答案

最坏的可能发生?你最终(不知不觉)与未NULL结尾的字符串,或继承整数一切正好是它的右侧,您打印到缓冲区的部分之后。然而,未终止字符串可能发生其他方面也是如此,即使你初始化缓冲区。

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.

要么是不希望的。但是,除非完全避开了动态分配的内存,最大静态分配的缓冲区通常是相当小的,这使得 memset的()相对便宜。事实上,比释放calloc最()的调用便宜得多动态块,这往往比大〜2K。

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包含有关默认初始化值的语言,我可以没有,但是,似乎使的gcc -std = C99 同意这一点,使用任何类型的存储。

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.

不过,有很多老的编译器(和编译器是不是很C99)仍然在使用,我preFER只使用 memset的()

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

这篇关于归零内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆