Initialize an array's pointed address on creation in C

552 views Asked by At

being a relative newbie in the automotive embedded development, I am currently facing a problem with a pointer which I need to initialize to a given address and who is later used to browse through the ROM of the microcontroller.

As my code must be MISRA-C 2004 compliant, I’d like to initialize this pointer on declaration without allocating new memory, which wouldn’t be used anyway, but, in order to avoid the “Don’t use pointer arithmetic” MISRA-error, I need it to be declared as an array.

Let me show you my current code for clarification:

static uint8* MemoryCursor_p = FIRST_ADDRESS_POINTED_BY_CURSOR;
/* Some cool stuff happens here*/
MemoryCursor_p = &( MemoryCursor_p [1]); /* Moving the cursor one byte forward in memory*/

This causes the MISRA check to trigger an error, as MemoryCursor_p is not defined as an array, but as a pointer. But if I declare it as an array, I am requested to define the pointed values, but I’d like to set the pointed address on declaration instead.

Of course, if I just try:

MemoryCursor_p += 1ul;

I am getting scolded by MISRA for using pointer arithmetic.

I’d like to avoid committing MISRA violations. Could someone please tell me how to proceed?

Just as an indication about these bits of code: this is part of the implementation of a simple CRC16 algorithm that does a checksum over some memory.

Thanks a lot!

2

There are 2 answers

4
Lundin On BEST ANSWER

You should never blindly follow MISRA, let alone blindly follow your static analyser warnings.

The mentioned rule 17.4 in MISRA-C:2004 didn't make any sense. It was rather a misguided attempt to prevent using *(x + i) instead of the clearer x[i]. But the rationale about out-of-bounds errors provided in the rule didn't make any sense and nobody could argue about why the *(x + i) form was less safe (apart from being less readable).

This rule has therefore been replaced in MISRA-C:2012. So the correct approach, in my opinion, is to create a company-wide deviation from the rule. Block all warnings related to 17.4.

In any case, you should not attempt to dodge the rule by using some fishy, obfuscated syntax. MemoryCursor_p++ is correct and the clearest form, use that. Alternatively, use a counter variable i and access array item number i. Either form is fine.

0
Andrew On

@Domack - there is a whole section at the front of the MISRA-C:2004 book on Deviations... and a whole book (MISRA C Compliance) now available which is equally applicable if you so wish! I agree with Lundin, that your best option is to raise a deviation, citing the changes in 2012