As I pointed out here:
http://www.misra.org.uk/forum/viewtopic.php?f=73&t=641
17.4 doesn't make sense from a safety point-of-view. MISRA agrees that it doesn't, but insists on keeping the rule for what seems to be code style reasons.
An expression like
x[3] = 0;
is by ISO C's definition equivalent with
*(x+3) = 0;
And the compiler will translate any [] expression to a *() expression. This is the reason why this horrible code is perfectly valid C:
3[x] = 0;
Because it will be translated to *(3 + x) = 0;
All these three syntax cases will yield exactly the same machine code and they will all merrily access an array out of bounds if given the chance. There is no safety argument for rule 17.4, it is just about coding style.
---
However, why would you ever want to return a pointer to an array? I always boldly state that no such case exists in a good program design, and so far nobody has been able to show me a single case where it makes sense to return pointers from functions.
A pointer returned from a function can point at the following kind of variables:
- Local variables. This case is always a bug in the program.
- The same data as one of the parameters of the function. This is poor programming, as the same parameter will be used twice in the function, taking up unnecessary stack space when the function is called. The C standard contains such functions, but then the C standard contains countless cases of poor programming practice, hence the need of subsets like MISRA-C.
- Dynamically allocated variables. Returning pointers to variables that were dynamically allocated inside the function is one of the most common causes for memory leaks in C programs. Instead, leave allocation to the caller. (Dynamic memory is banned by MISRA-C anyhow.)
- Global variables. This is a bug in a multi-process environment, as it might make the function unsafe for multiple processes. The function will also become sensitive to the order of evaluation, in case the function is called twice in the same expression (ie implementation-defined behavior, which you aren't allowed to rely on in MISRA-C).
- Static variables. This is a bug in a multi-process environment, as it might make the function unsafe for multiple processes. The function will also become sensitive to the order of evaluation, in case the function is called twice in the same expression (ie implementation-defined behavior, which you aren't allowed to rely on in MISRA-C). This is also a flaw in the program design, as it breaks the encapsulation of private variables.
So please tell me of a case where it makes sense to return a pointer from a function.