UNINIT.HEAP.MUST

Uninitialized heap use

The UNINIT.HEAP.MUST checker looks for heap memory allocated with malloc that hasn't been initialized before it's used.

Vulnerability and risk

Using uninitialized heap memory can result in significant performance irregularities for your code, as the values assigned to an given data object are randomly picked from the heap memory allocated and could reflect the state of previously-used objects or objects from another process. If the software doesn't initialize memory correctly, unexpected results can occur, possibly with security implications.

Mitigation and prevention

Heap memory is always uninitialized on return from the popular allocation function malloc(). To avoid uninitialized memory problems, make sure all variables and resources are initialized explicitly before their first usage.

Another alternative is to use the standard calloc() library function, which automatically initializes all allocated memory to zero.

Vulnerable code example 1

Copy
  #include<stdlib.h>
  
  typedef struct {
    int x;
  } S1;
  
  typedef struct {
    S1* ptr;
 } S2;
 
 void foo(S1* ptr) {
   int k = ptr ? ptr->x : -1;
 }
 
 int main() {
   S2* ps = (S2*)malloc(sizeof(S2));
   if( ps != NULL ) {
     foo(ps->ptr);
     free(ps);
   }
   return 0;
 }

Klocwork flags line 18, indicating that variable 'ps->ptr', which gets its value from the memory allocated at line 16, is used uninitialized at line 18.

Fixed code example 1

Copy
  #include<stdlib.h>
  
  typedef struct {
    int x;
  } S1;
  
  typedef struct {
    S1* ptr;
 } S2;
 
 void foo(S1* ptr) {
   int k = ptr ? ptr->x : -1;
 }
 
 int main() {
   S2* ps = (S2*)calloc(1, sizeof(S2));
   if( ps != NULL ) {
     foo(ps->ptr);
     free(ps);
   }
   return 0;
 }

In the fixed code, the call to malloc() is simply replaced with a similar call to calloc(), to be sure that the memory allocated is pre-initialized to zero. This saves having to manually initialize each element of the 'S2' structure before using the pointer 'ps'.

Vulnerable code example 2

Copy
  #include<stdlib.h>

  typedef struct {
      int x, y;
  } S1;

  int foo(S1* ptr) {
      return ptr->x * ptr->y;
  }

  int main() {
     S1* ps = (S1*)malloc(sizeof(S1));
     if( ps != NULL ) {
         foo(ps);
         free(ps);
     }
 }

Klocwork flags line 14, as the memory allocated at line 12 is used uninitialized at line 14.

Fixed code example 2

Copy
  #include<stdlib.h>

  typedef struct {
      int x, y;
  } S1;

  int foo(S1* ptr) {
      return ptr->x * ptr->y;
  }

 int main() {
     S1* ps = (S1*)malloc(sizeof(S1));
     if( ps != NULL ) {
         ps->x = 32, ps->y = 64;
         foo(ps);
         free(ps);
     }
 }

In the fixed code, rather than using the calloc() function to allocate the memory, we have explicitly initialized the members of the structure 'S1' so that when the values are read from the pointer 'ps' they are already known to be valid.

Related checkers