Main Content

Unprotected dynamic memory allocation

Pointer returned from dynamic allocation not checked for NULL or nullptr value

Description

This defect occurs when you access dynamically allocated memory without first checking if the prior memory allocation succeeded.

Risk

When memory is dynamically allocated using malloc, calloc, or realloc, it returns a value NULL if the requested memory is not available. If the code following the allocation accesses the memory block without checking for this NULL value, this access is not protected from failures.

Fix

Check the return value of malloc, calloc, or realloc for NULL before accessing the allocated memory location.

int *ptr = malloc(size * sizeof(int));

if(ptr) /* Check for NULL */ 
{
   /* Memory access through ptr */
}

Examples

expand all

#include <stdlib.h>

void Assign_Value(void) 
{
  int* p = (int*)calloc(5, sizeof(int));

  *p = 2;  
  /* Defect: p is not checked for NULL value */

  free(p);
}

If the memory allocation fails, the function calloc returns NULL to p. Before accessing the memory through p, the code does not check whether p is NULL

Correction — Check for NULL Value

One possible correction is to check whether p has value NULL before dereference.

#include <stdlib.h>

void Assign_Value(void)
 {
   int* p = (int*)calloc(5, sizeof(int));

   /* Fix: Check if p is NULL */
   if(p!=NULL) *p = 2; 

   free(p);
 }
#include <stdlib.h>
#include<string.h>
typedef struct recordType {
    const char* id;
    const char* data;
} RECORD;

RECORD* MakerecordType(const char *id,unsigned int size){
    RECORD *rec = (RECORD *)calloc(1, sizeof(RECORD));
    rec->id = strdup(id);

    const char *newData = (char *)calloc(1, size);
    rec->data = newData;
    return rec;
}

In this example, the checker raises a defect when you dereference the pointer rec without checking for a NULL value from the prior dynamic memory allocation.

A similar issue happens with the pointer newData. However, a defect is not raised because the pointer is not dereferenced but simply copied over to rec->data. Simply copying over a possibly null pointer is not an issue by itself. For instance, callers of the recordType_new function might check for NULL value of rec->data before dereferencing, thereby avoiding a null pointer dereference.

Result Information

Group: Dynamic memory
Language: C | C++
Default: Off
Command-Line Syntax: UNPROTECTED_MEMORY_ALLOCATION
Impact: Low

Version History

Introduced in R2013b