Rule 9.2 in TC1

6.9 Initialisation

Moderators: misra-c, david ward

Posts: 70
Joined: Mon Dec 10, 2007 1:57 pm

Rule 9.2 in TC1

Post by Lundin » Wed Feb 20, 2008 2:53 pm

I question the practical use of the text added to rule 9.2 in TC1. According to that rule, zero initialization of an array or struct can only occur at top level.

How do you write MISRA-C compatible code for this case:

Code: Select all

typedef struct
  BOOL enabled;
  uint8_t buffer [5000];

} DataBuffer;

DataBuffer db = {TRUE};            /* not compliant, non-zero initialization */
DataBuffer db = {TRUE, {0} };      /* not compliant, zero initialization at sub level*/

DataBuffer db = {TRUE, /* what goes here? */ };

As the rule is now, the programmer who happens to have a data structure like the one above will have to type out 5000 zeroes in his source file to conform to MISRA-C.

I don't see why the second of those lines can't be allowed. The two non-compliant examples above are perfectly safe and will set the whole buffer to zero. ISO C is clear:
ISO 9899:1999, chapter 6.7.8 Initialization wrote: 21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or
fewer characters in a string literal used to initialize an array of known size than there are elements in the array,
the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
(I can only cite C99, not C90, though they are identical in this case)

The buffer is implicitly initialized as if it had static storage duration and is therefore set to zero.

The argument "the struct can be initialized to zero and the Boolean member can then be set to TRUE in runtime" is not valid, as the struct might be const.

Posts: 566
Joined: Thu Jan 05, 2006 1:11 pm

Post by misra-c » Tue Feb 26, 2008 4:17 pm

The purpose of Rule 9.2 is to ensure that initialiser for an object with aggregate type reflects the structure of that type in its brace nesting.

As originally stated, the rule recognised that all elements of an object with aggregate type could be initialised to 0 by explicitly initialising the first element only. The change introduced in TC1 restricted this type of initialisation to top-level aggregates only.

In retrospect the TC1 restriction is not helpful. As you have pointed out, it requires explicit entry of a sub-aggregate initialiser and this could be impractical if there is a large number of elements. Also, from a maintenance point of view, it can be easier not to have to write the initialiser explicitly.

This matter will be taken into consideration for future developments of MISRA C. In the meantime you could choose to deviate Rule 9.2 in the circumstances you have described.
Posted by and on behalf of
the MISRA C Working Group


Return to “6.9 Initialisation”