UNINIT.HEAP.MIGHT

Uninitialized heap use possible

The UNINIT.HEAP.MIGHT checker looks for heap memory allocated with malloc that may not have 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

Copy
  struct s {
    int i;
  };
  
  int f(struct s **v, int t) {
    *v = (struct s *)malloc(sizeof(struct s));
    if (t > 0) {
      (*v)->i = t;
    }
   return (*v)->i;
 }

Klocwork flags line 10, indicating that variable '(*v)->i', which gets its value from the memory allocated at line 5, might be used uninitialized at line 10.

Related checkers