Rule 8-5-2: what about strings?

Moderators: david ward, misra cpp

Post Reply
Posts: 1
Joined: Tue Jan 09, 2018 5:22 pm
Company: Vapor Rail

Rule 8-5-2: what about strings?

Post by jocob » Wed Jan 10, 2018 1:15 pm

struct Test
char str1[20];
char str2[20];

struct Test t =

LDRA flags this with 397 S (Array initialisation has insufficient items.) violation of 8-5-2 (Braces shall be used to indicate and match the structure in the non-zero initialization of arrays and structures.)

Looking at the details of the rule in the guidelines, I see why: "The non-zero initialization of arrays or structures requires an explicit initializer for each element."

It seems there should be an exception for initializing a character array with the string syntax, since:
a. the unused characters are implicitly null character 0
b. there is no MISRA compliant way to explicitly add null characters to a "string"

I think MISRA C 2004 has a similar problem, but I haven't looked at 2012 yet.

Posts: 117
Joined: Wed Apr 27, 2016 2:33 pm
Company: Elektrobit Automotive GmbH

Re: Rule 8-5-2: what about strings?

Post by dg1980 » Thu Jan 11, 2018 8:16 am


what´s the output of LDRA if you use this ugly alternative?

Code: Select all

struct Test t =
  {'H', 'e', 'l', 'l', 'o', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0'},
  {'W', 'o', 'r', 'l', 'd', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0'}

misra cpp
Posts: 161
Joined: Mon Jun 02, 2008 1:55 pm
Company: MISRA

Re: Rule 8-5-2: what about strings?

Post by misra cpp » Thu Jan 18, 2018 9:16 am

You are correct that the example initializing using "Hello" etc. is a violation of 8-5-2 (and dg1980's example padded with '\0's is compliant). However, the first example would be compliant under MISRA C:2012 - it has the exception for strings.

The next issue of MISRA C++ aims to remove unnecessary differences between MISRA C and C++, and this is likely to be a rule that will be modified for that reason - though they may still not be identical because there is a semantic difference between C and C++ for a statement like
char str[4] = "abcd";
(its legal in C but a constraint error in C++)

As a matter of etiquette, we don't encourage discussion of particular tool's behaviour on the Bulleting Board - good or bad
Posted by and on behalf of
the MISRA C++ Working Group

Post Reply

Return to “6.8 Declarators (C++)”