Pointer to non-initialized value converted to const pointer

Pointer to constant assigned address that does not contain a value

Description

This defect occurs when a pointer to a constant (const int*, const char*, etc.) is assigned an address that does not yet contain a value.

Risk

A pointer to a constant stores a value that must not be changed later in the program. If you assign the address of a non-initialized variable to the pointer, it now points to an address with garbage values for the remainder of the program.

Fix

Initialize a variable before assigning its address to a pointer to a constant.

Examples

expand all

#include<stdio.h>

void Display_Parity()
 {
  int num,parity;
  const int* num_ptr = &num;  
  /* Defect: Address &num does not store a value */

  printf("Enter a number\n:");
  scanf("%d",&num);

  parity=((*num_ptr)%2);
  if(parity==0)
    printf("The number is even.");
  else
    printf("The number is odd.");

 }

num_ptr is declared as a pointer to a constant. However the variable num does not contain a value when num_ptr is assigned the address &num.

Correction — Store Value in Address Before Assignment to Pointer

One possible correction is to obtain the value of num from the user before &num is assigned to num_ptr.

#include<stdio.h>

void Display_Parity()
 {
  int num,parity;
  const int* num_ptr;

  printf("Enter a number\n:");
  scanf("%d",&num);

 /* Fix: Assign &num to pointer after it receives a value */ 
  num_ptr=&num;                     
  parity=((*num_ptr)%2);
  if(parity==0)
    printf("The number is even.");
  else
    printf("The number is odd.");
 }

The scanf statement stores a value in &num. Once the value is stored, it is legitimate to assign &num to num_ptr.

Result Information

Group: Data flow
Language: C | C++
Default: Off
Command-Line Syntax: NON_INIT_PTR_CONV
Impact: Medium
Introduced in R2013b