Properly clearing an array

82 views Asked by At

I've seen two different ways to fill a char[] with 0 (in this example, upon initialization):

/* method 1 */
char foo[1024] = {0};

/* method 2 */
char foo[1024];
memset(foo, '\0', sizeof(foo));

What are the main differences between the two codes? How do they differ in functionality, etc?

4

There are 4 answers

3
alk On BEST ANSWER

What are the main differences between the two codes?

In case 1 the array is zeroed out from the moment it can be used, as it got initialised.

In case 2 its content is well defined only after the call to memset().

The essential difference is that for case 2 there is is gap where foo's content is "garbage". This isn't the case for case 1.

5
Wasi Ahmad On

The first way is generally better, since it zero initializes all members. Mem setting to 0 is not always the same as zero initializing, particularly for floating point and pointer members, which may have 0 values that aren't all bits zero.

Performance wise, I don't know which would be faster, you'd have to measure it. By the way, you can use 0 instead of '\0' in memset.

memset(foo, 0, sizeof(foo));
0
user3629249 On
/* method 1 */
char foo[1024] = {0};

in method 1, the setting of the array occurs at program load time, usually from a literal and can only occur once for each entry into the 'scope' of the array.

/* method 2 */
char foo[1024];
memset(foo, '\0', sizeof(foo));

in method 2, the setting of the array occurs at runtime, consumes runtime CPU cycles, and can occur as many times as needed.

1
M.M On

The effect of these two codes is the same. Probably a compiler will generate the same assembly in both cases. However the first one is easier to read and maintain.

There is no possible way you can accidentally write the wrong length of data with the first one.

Further, the = { 0 }; idiom can be used to initialize all named arrays and structures: integers get 0 value, floating point get 0.0 , and pointers get a null pointer. Only the first of those three things is guaranteed for the memset version.

So if you are writing portable code, you'll need to use = { 0 } sometimes anyway -- so you may as well use it every time.