0

Is there any disadvantage of initializing an array with zeroes as

 int a[5] = {0};

In many places, I have seen people using memset or a loop for initialization. Is there any security threat for this?

chelsea
  • 185
  • 1
  • 10
  • 3
    This is a good idea and those people probably didn't know that this option existed – M.M Sep 09 '18 at 05:52
  • 3
    The initializer won't perform worse than `memset()` and probably performs better than a loop. – Jonathan Leffler Sep 09 '18 at 05:55
  • If the array is going to be immediately loaded from a file/network/whatever, then the initialization is a waste of cycles. It can also can be a wasteful band-aid that covers up problems during testing. – Martin James Sep 09 '18 at 06:17
  • If the array is going to be immediately loaded from a file or the network, then there will be I/O that will take much MUCH longer than setting the array to zero (which, by the way, helps avoid an entire class of sometimes serious bugs). So there is no reason not to be safe and put your array in a known consistent state. – torstenvl Sep 09 '18 at 06:31
  • @torstenvl s/avoid/cover-up 'So there is no reason' well, obviously not true. Would you hold the same opinion if each buffer was 1MB? – Martin James Sep 09 '18 at 06:41
  • @MartinJames: If the buffer is 1MB you have bigger problems, such as stack overflow. – John Zwinck Sep 09 '18 at 07:02
  • 1
    If the array needs to be initialized to all zero, well then initialize it to all zero, otherwise don't. It's as simple as that. – Jabberwocky Sep 09 '18 at 07:31
  • "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." -Knuth. If the initialization is followed by another assignment, a good compiler will optimize it away anyway. If not, you've avoided a serious security hole. – torstenvl Sep 09 '18 at 16:22
  • @torstenvl the 'assignment ' is often passing the address to an external system call, and the compiler will not optimize it away. There are loads of examples on SO of pointless zeroing of [buffer] and then reading 'buffer' bytes in. Result - the subsequent calls to linrary functions that require a NUL terminator fail only when the buffer is completely filled by the read - intermittent bug that appears under heavy load. Such zero-filling is not avoidance of premature optimization - it's usually just a sign of sloppy programming:) – Martin James Sep 18 '18 at 21:39

0 Answers0