Electronic – Memory allocation in embedded software development

cembedded

In embedded systems, the use of dynamic allocation is strongly discouraged. MISRA C do not allow using malloc and calloc because of their unexpected behaviour. My question is: How do you handle memory allocation when you have no idea how much space you need ? How do you initialise an array before using it ? In the example below, is it really better to allocate 1000 values and end up using 30 values because you don't know how many values you really need ?

#define MY_ARRAY_MAX_SIZE 1000
/**
* 
* some code ...
*/

// Init
uint8_t myArray[MY_ARRAY_MAX_SIZE];                              // Approach 1

uint8_t myArray[MY_ARRAY_MAX_SIZE] = {0}                         // Approach 2
/* OR */
memset((void *)myArray, (uint8_t)0, MY_ARRAY_MAX_SIZE * sizeof(uint8_t)); // Approach 3

Best Answer

In the example below, is it really better to allocate 1000 values and end up using 30 values because you don't know how many values you really need ?

In my experience, this is not a problem I've actually faced. Requirements tend not to be that dynamic.

If you have, say, 12 8-bit ADC channels you need to datalog every minute for a rolling 1 day period then you know that you need a buffer of 1440 * 12 uint8_t elements and can statically allocate that.

The closest you generally come to your hypothetical is things like UART rx buffers. The solution here is to allocate a larger buffer that you determine you will need. This isn't a problem useless you are short of RAM, and the amount of slack doesn't usually need to be large.

And, as others have said, dynamic allocation isn't considered harmful in embedded systems if it is done properly. I do tend to avoid it though because it significantly increases design complexity and testing requirements.