Before initialization, both automatic variables and allocated memory contain junk data. Attempting to read or use uninitialized automatic variables or memory can cause unexpected results. Therefore variables and memory should always be initialized before being read.


Note that this rule applies to memory obtained through ``++alloc++``, ``++malloc++``, ``++realloc++``, ``++valloc++`` and ``++reallocf++``.


== Noncompliant Code Example

----
int fun(int i) {
  int a; // currently contains garbage value
  char *buf = malloc(sizeof(char) * 21); // currently contains garbage value

  if (a > i )  // Noncompliant; a uninitialized
  {
    return strlen(buf); // Noncompliant; strlen reads its argument
  }
  return i;
}
----


== Compliant Solution

----
int fun(int i) {
  int a = 0;
  char *buf = cmalloc(sizeof(char) * 21); // calloc 0-initializes the allocated memory

  if (a > i )
  {
    return strlen(buf); // returns 0;
  }
  return i;
}
----


== See

* https://wiki.sei.cmu.edu/confluence/x/AdYxBQ[CERT, EXP33-C.] - Do not read uninitialized memory
* https://wiki.sei.cmu.edu/confluence/x/EXw-BQ[CERT, EXP53-CPP.] - Do not read uninitialized memory
* http://cwe.mitre.org/data/definitions/119.html[MITRE, CWE-119] - Improper Restriction of Operations within the Bounds of a Memory Buffer
* http://cwe.mitre.org/data/definitions/665.html[MITRE, CWE-665] - Improper Initialization


ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)

include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]
