malloc函数分配失败处理的严重性

本次在实际测试情况下,发现程序无缘无故的异常,导致看门狗超时复位,经过排查是malloc函数分配失败的时候,依然对指针进行了操作,导致异常。以前没重视这个问题是因为,总觉的malloc基本都会成功的,假如循环调用一个函数logOutput,里面有malloc和free,那么下次调用logOutput分配相同的空间应该也是成功的(实际上非我所愿)。问题函数如下,必须对pBuffer没有分配成功做处理,否则很容易出问题。

static inline void logOutput(uint32_t level, const char *tag, const char* format, ...)
{
    va_list va;
    int len, len2,space;
    char* pBuffer;
pBuffer
= (char*)malloc(512); /*space "\n\0"*/ if(pBuffer == NULL) return; space = gLogBufferLength - 2; len = utils_snprintf(pBuffer, LOG_PREFIX_SIZE_MAX, "#%s,%d:", tag,level); utils_snprintf( pBuffer, LOG_PREFIX_SIZE_MAX, "#%s,%d:", tag,level); space -= len; va_start(va, format); len2 = utils_vsnprintf( pBuffer+len, space ,format, va); va_end(va); len += (len2>0?len2:space); if(len < gLogBufferLength - 2){ pBuffer[len] = '\n'; pBuffer[len+1] = '\0'; }else{ pBuffer[gLogBufferLength - 5] = '.'; pBuffer[gLogBufferLength - 4] = '.'; pBuffer[gLogBufferLength - 3] = '?'; pBuffer[gLogBufferLength - 2] = '\n'; pBuffer[gLogBufferLength - 1] = '\0'; } logwrite((uint8_t*)pBuffer,utils_strlen(pBuffer)); free(pBuffer); };

 

posted @ 2018-03-15 14:34  429512065  阅读(1392)  评论(0编辑  收藏  举报