1

I have global pointer to the array, lets say that it has declaration like shown below.

uint8_t * g_ptr;

I have some function

void foo(uint8_t no_devices);

which will be used to allocate arrays of desired size.

Pointer returned by function malloc() will be stored in g_ptr. This will work like champ if dynamic allocation is successful, but what if malloc() return NULL value.

I have an idea how to handle this kind of error and just want to get your opinion.

do
{
  g_ptr = (uint8_t *) malloc(no_devices * 8);
}
while(g_ptr == NULL)

Is this good idea, or is there another way to handle this kind of errors?

I am using avr-gcc compiler.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
AC Voltage
  • 339
  • 3
  • 9
  • 1
    Well, that's likely to eat all your CPU and drain your battery, so I guess it will "fix" the problem by shutting down the device after a bit. – Mat Feb 18 '18 at 21:28
  • 7
    Whea, usually when malloc return NULL it mean that memory is exhausted so you're screwed. In an other hand I never use dynamic allocation on microcontroller, I would have done a array or MAX_DEVICES size.. – alkaya Feb 18 '18 at 21:35
  • 4
    I don't think this is a good strategy. When `malloc` returns `NULL` it's usually because you are out of memory, the fact that you keep requestion memory won't probably change the outcome. At least put a delay of 1 sec and hope that in that time other processes ended/freed the memory. Most of the times that means that you program cannot continue anyway, printing an error message and exiting would be more appropriate. – Pablo Feb 18 '18 at 21:49
  • https://stackoverflow.com/a/1726006/6385115 –  Feb 18 '18 at 22:22
  • Don't use malloc(). Figure out what memory you need and allocate it statically. If it doesn't fit, use less memory or design in a MCU part with more. – TomServo Feb 19 '18 at 15:04
  • 1
    Thank you for you answers. I did have version of the code where I used Macro to define size of the array, and after reading this answers I will use that version instead of this one. – AC Voltage Feb 19 '18 at 17:37
  • It depends on environment. In FreeRTOS you can control allocation strategies as it delivers malloc itself. You could also wrap malloc with own version that does safety check and halts/restart MCU on such event. – andy Mar 15 '18 at 11:55

0 Answers0