cap29
cap29

Reputation: 996

Difference between memset and initialization (array)?

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?

Upvotes: 2

Views: 177

Answers (2)

jamesdlin
jamesdlin

Reputation: 90105

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.

Upvotes: 1

dbush
dbush

Reputation: 224387

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.

Upvotes: 4

Related Questions