Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zeroing out memory

Tags:

c

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:

char buffer[1024] = {0}; 

Which will zero all bytes.

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?

like image 957
ant2009 Avatar asked May 21 '10 17:05

ant2009


People also ask

Does Free Clear memory?

The free() function is used to deallocate memory while it is allocated using malloc(), calloc() and realloc(). The syntax of the free is simple. We simply use free with the pointer. Then it can clean up the memory.

Does Linux zero out memory?

No, Linux does not zero its menory after releasing it. Most libraries implement zeroing the memory while allocating it, but this is programming language dependent and can be overridden.


1 Answers

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()

like image 109
Tim Post Avatar answered Oct 04 '22 08:10

Tim Post