c++arraysmisra

How to read uint8_t array and convert into char array in C++ and also match MISRA rule?


I have test this code and result is correctly, but will got "567 S Pointer arithmetic is not on array." in line24 "arr++;", does anyone know how to fix it?

#include <iostream>

using namespace std;

int PartNum_Read(char* arr);

int PartNum_Read(char* arr)
{
    uint32_t ret = 0U;
    uint8_t ReadPartNumer[3]={'a','b','c'}; //copy from other function, type is uint8_t
    if(arr != NULL)
        {
            for(int j = 0U; j < sizeof(ReadPartNumer); j++)
            {
                *arr = static_cast<char>(ReadPartNumer[j]);
                 arr++;
            }
            ret = (sizeof(ReadPartNumer));
        }
    cout << "PN: " << *arr << endl;
    
    return ret;
}

int main()
{
    cout<<"Hello World\n";
    char PartNumer[3]={0};
    PartNum_Read(&PartNumer[0]);
    for(int i = 0U; i < 3; i++)
    {
        cout << "PN: " << PartNumer[i] << endl;
    }
    return 0;
}

Solution

  • The older MISRAs like C:2004 and C++:2008 had various confused rules regarding pointer arithmetic. The recommendation is to upgrade to MISRA C:2012 or later.

    The "fix" in this case is as stupid as the rule:

    int PartNum_Read (char arr[])
    

    Yes, that so-called "fix" doesn't make any difference at all in practice. But it should make the code compliant to MISRA C++:2008.

    The root problem here is a failure to understand pointer arithmetic when these guidelines were written. It's a common misconception, as addressed here: Do pointers support "array style indexing"? But these known MISRA problems have been fixed since long, at least on the C side.