SpiderElectron

Electronic Engineering Blog

Bug hunting : malloc failed :-(

I’ve been tracking down an elusive bug which was causing one of my devices to occasionally start mis-behaving. The device would respond slowly (if at all) to some commands, and respond normally to others.

It was pretty obvious what the issue was when I attached the debugger and started single-stepping through the code while it was misbehaving.

I landed on the ‘return’ in this code:

prevLen = sizeof(LIST_ITEM)+32;
 pWorkItem = malloc(prevLen);
if(pWorkItem == 0)
 return 0;

so it was obvious I was getting a malloc fail, which meant I had ran out of memory somewhere along the line. The ‘return 0’ meant that the command silently failed, without any feedback to the user.

I quickly looked through the remainder of this function and found that the memory which was malloc’d was never freed, so I made two changes.
First I ensured that the memory was freed as soon as we were finished with it, and additionally I added some feedback to the external interface like this:

prevLen = sizeof(LIST_ITEM)+32;
 pWorkItem = malloc(prevLen);
if(pWorkItem == 0)
 {
 sprintf(txBuf,"$ERR:MIM-MALLOC FAIL at %d in %s\r",__LINE__, __FILE__);
 UART_Merc_PutString(txBuf);
 return 0;
 }

The UART_Merc_PutString sends data to a debug terminal.

With these fixes in place it’s all working sweetly now.

, , ,

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.