Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rule 0.1.9 - is zero-initialization considered "dead code"?
#1
Consider the following example:

Code:
// third_party.h
struct Foo
{
   int32_t a;
   int32_t b;
};

// client.cpp
Foo create()
{
  Foo f{};     // Violates Rule 0.1.9?
  f.a = 123;
  f.b = 321;
  return f;
}

Does that violate Rule 0.1.9? While the initialization may be redundant, it serves a purpose as defensive programming. If we remove the zero-initialization, we risk having some members of "Foo" uninitialized, especially if we bump to a new version of "third_party.h" that adds a new member to the struct. It's safer to zero-initialize at the declaration, to ensure no members remain uninitialized.

It's also preferable to initialize like this instead of "Foo f{123, 321};", because we can see written in code which field gets which value. We need to wait until C++20 to get designated initializers in C++ to initialize everything in one line.

Thanks!
Reply
#2
Strictly this does not violate  0.1.9, because the statement that declares f cannot be removed and still leave working code, but it may be seen as zero initialising followed by assignment (i.e. the zero initialisation is redundant) which violates 0.1.6.
Posted by and on behalf of
the MISRA C++ Working Group
Reply
#3
Thanks, it appears that my static analyzer mistakenly mapped the error message to 0.1.9.

I read now the discussion about 0.1.6:

https://forum.misra.org.uk/showthread.php?tid=1522

MISRA have previously stated that 0.1.6 is intended for DU anomalies only, so it does not appear this case falls under that category?

I also note that MISRA C++ 2023, rule 0.1.1, function f5() marks a very similar example as compliant. Is that also compliant under MISRA C++:2008?
Reply
#4
You're right, your example should be compliant in both 2008 & 2023.

However, we think we've made a mistake in not allowing overwriting zero initialisation
This will be clarified in the next edition.
Posted by and on behalf of
the MISRA C++ Working Group
Reply


Forum Jump:


Users browsing this thread: 5 Guest(s)