質問

While traversing Wikipedia following some links, I stumbled across the following code example that initializes a char buffer to 0, but then memsets it to 0 before use. Is this necessary? If so, why? The reason I ask is that I am no expert, and the example clearly states that this was the coder's intention with the comment "/* Really initialized to zeroes */" on the memset, as opposed to "/* initialized to zeroes */" on the initialization.

EDIT: Note, I've rolled back the edit on the wikipedia page that caused this, so it is no longer visible in the link.

役に立ちましたか?

解決

char buffer[5] = {0};  /* initialized to zeroes */

/* some declaration / statements, but no access to buffer object */

memset ( buffer, 0, sizeof buffer); /* Really initialized to zeroes */

in the above code, the call to memset is totally useless. buffer is already guaranteed to be initialized to 0.

他のヒント

Following up on ouah's answer. If you have

char buffer[5] = { 0 } ;

int main(int argc, char **argv)
{
    memset ( buffer, 0, sizeof buffer);
    ...

There might be one exception: If you really do low level C programming (without an operating system) and your C program is called directly without a fully working environment, then the buffer array might not be initialized correctly in this case, because the necessary initialization code (the code running before main) is missing.

In this case it's the other way round: The initialization is useless (because it does not work in this particular environment) and the memset is necessary.

But as I said: This really only happens with extreme low level C programming and is actually a bug in the environment, which gives you a non-C conforming environment.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top