We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
The answer seems obvious, but considering this MISRA rule
Rule 11.5 A conversion should not be performed from pointer to void into pointer to object
would it not be safer to have memory allocation functions like "malloc" return a pointer to a char* instead? This type of pointer has no alignment issues.
Thanks.
Ah, conversion to/from void* is implicit. Do that is a part of the answer.
A char* has no alignment issues. But that is irrelevant for all the times when you are allocating objects of a type that does have alignment issues.
Note that malloc() can't know what type you are allocating. And so can't know what the alignment requirements may be. So the only workable solution is for malloc() to always produce a pointer of the "best" possible alignment class that the processor might require. This means it's safe to type cast the returned pointer into a pointer to int or a pointer to double or whatever you need.
MISRA has to limit itself into what is possible by the programming language. And malloc() is part of the C language standard. But the goal with the MISRA rule isn't to point finger at malloc(), but to make sure that people don't try to send random void pointers as parameters or store in structs just to later decide what to recast the pointers into. So developers should avoid trying to implement abstract data types centered around "base class" code that operates on void pointers.
Well, MISRA is not in a position to overturn decisions made by the ISO standard committee about the C programming language, some 25 years ago.
But that's irrelevant anyway, because you're overlooking MISRA 2004 Rule 20.4, which forbids any use of malloc() & friends.
MISRA or not - dynamic memory isn't a great idea in embedded devices with long uptimes. Too much problems with fragmented heap, resulting in failed memory allocations even if there are lots of free memory.
Thanks folks.