Reading of uninitialized memory

If your program tries to read from memory that was allocated but not written to, the program will generate a memory error because the memory is uninitialized.

Consequences

Using uninitialized memory generates a random data read runtime error.

Detecting the error

There's no specific UI field to enable the detection of this type of error. The Memory Analysis tool often doesn't detect it, except when your program reads uninitialized data from a recently allocated memory block. For the list of functions that trap this error, see the Trap Function field below.

Information returned by the Memory Problems view

The notification for this type of memory error includes the following details:
  • Severity: ERROR
  • Description:
  • Pointer: address of the memory block containing uninitialized data
  • Trap Function: any str*() or mem*() function that follows an allocation operation
  • Alloc Kind: how memory was allocated for this block (malloc, calloc, or realloc)
  • Location: source file and line of code where the error occurred (e.g., main.c:59)
  • Count: number of blocks involved

How to address random data read issues

Write data to any new memory block as soon as possible after the call to malloc, before you access the pointer to read the memory. Or, use calloc, which always initializes the memory with zeros (0).

Example

The following code demonstrates an uninitialized memory read (which occurs if the program is called with no arguments):
int main(int argc, char ** argv){
  char * ptr = NULL;
  ptr = malloc(13);
  if (argc > 1)
     strcpy(ptr,"Hello World!");
  ...
  ptr[12]=0;
  printf("%s\n",ptr);
  return 0;
}