zeroing memory area of a structure in c

Viewed 257

I have following structure and i want to initialize it to zero.

struct example {
     int a;
     int b;
     char c;
};
struct example mystruct;

I can memset mystruct to zero in following ways:

memset(&mystruct, 0, sizeof(mystruct));

or

mystruct = (struct example) {0};

Is the second way is equal to the first one?

Note that i want to initialize mystruct variable to zero not only at variable definition, maybe for reusing it.

2 Answers

Well, in your case, they will be equivalent (disregarding the padding bytes).

Quoting C11, chapter §6.7.9/ P21, (emphasis mine)

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

and, regarding the initialization of static storage duration objects, P10 (again emphasis mine)

[...] If an object that has static or thread storage duration is not initialized explicitly, then:

— if it has pointer type, it is initialized to a null pointer;

— if it has arithmetic type, it is initialized to (positive or unsigned) zero;

— if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

— if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;


For sake of completeness, as mentioned in the below comment by Serge Ballesta:

all remaining members will be initialized implicitly the same as objects that have static storage duration. And the standard does not mandate anything for the padding bits of the top level object

which indicates, the assignment will differ from the memset() call in case of the first object / member, for the padding values.

No, they are not equal.

The first is more low-level, it will set all bits of the value to 0, including those that are not part of any member (padding).

The latter is only guaranteed to set the actual members to zero, so it might be faster since it has the opportunity to touch less memory.

Related