I made a function for adding next numbers in the array. Code is very simple, like following
int math(int *address, int size)
{
int sum = 0;
for (int i = 0; i < size; i++)
{
sum += *address;
address++;
}
return sum;
}
During static analysis I found, that there is problem against MISRA rule - which is saying that you can do math only on pointers assigned to an array. Purpose of this function is to use it on arrays, but of course - what I wrote in here is not guarantee that pointer won't be assigned to a variable.
One work-around which I think about is to copy whole table to local area and then sum all elements, but it's rather big operation, wasting lot of uprocessors assets. Do you have any ideas how can I make it better?
This would be from MISRA-C:2004 chapter 17, which was rather irrational about the use of pointers and arrays. This chapter was rewritten from scratch in MISRA-C:2012 (chapter 18). I would strongly recommend to upgrade, since MISRA-C:2004 simply doesn't make much sense here.
As for how to make your code MISRA-C:2004 compliant, do this:
int math(int address[], int size)
{
int sum = 0;
int i; // declaration must be here, MISRA-C:2004 does not allow C99
for (i = 0; i < size; i++)
{
sum += address[i];
}
return sum;
}
Yes it does the very same thing. But at least it made your code slightly more readable.
To make your code even safer, although not compliant with any MISRA, do this:
// better than MISRA-C but not compliant
int math(size_t size, int address[size])
{
int sum = 0;
for (size_t i = 0; i < size; i++)
{
sum += address[i];
}
return sum;
}
Or in case of high integrity systems, you could even do:
int math(size_t size, int (*array)[size])
{
int* address = *array;
...
Both of these alternatives give safer code than MISRA-C.