2

I've been working with some C code and I would like to know what the difference is between next codes:

double myArray[5] = {0,0,0,0,0};

and

double myArray[5];
memset(myArray,0,5*sizeof(double));

Could there be a problem for replacing the second one with the first one? If so, what kind of problems might be?

2 Answers 2

4

Using memset this way makes assumptions regarding the representation of floating point numbers, specifically that the representation of all bits 0 corresponds to the value 0.

If your system uses IEEE754 floating point representation (as are most systems you're likely to come across) this assumption holds. However, if you find yourself running your code on some exotic system that does not, then you might not get the result you expect.

Sign up to request clarification or add additional context in comments.

4 Comments

Incidentally, there was some regret in the IEEE-754 committee that a memset to −1 (255) would not fill an array with signaling NaNs. It is so close and just would have required specifying the sense of a signaling/quiet bit in the original standard.
This is the best site I've ever visited.
Thank you very much. Could you add to your answer what kind of problems might be? I'd help a lot if you could give an example or a case.
@Carlos I've heard of systems where a NULL pointer is not all bytes 0, though I've never personally came across such a system.
1

In addition to dbush's answer, although there likely wouldn't be a problem on most modern systems using memset, the memset version (as written) is more brittle. If someday you decided to change the size of myArray, then one of two things would happen with the version using the braced initializer list:

  • If you decreased the size of myArray, you will get a compilation error about having too many initializers.
  • If you increased the size of myArray, any elements without an explicit initializer will automatically be initialized to 0.

In contrast, with the memset version:

  • If you decreased the size of myArray without remembering to make a corresponding change to memset, memset will write beyond the bounds of the array, which is undefined behavior.
  • If you increased the size of myArray without remembering to make a corresponding change to memset, elements at the end will be uninitialized garbage.

(A better way to use memset would be to do memset(myArray, 0, sizeof myArray).)

Finally, IMO using memset in the first place is more error-prone since it's quite easy to mix up the order of the arguments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.