Main Content

Partially accessed array

Array partly read or written before end of scope

Description

This defect occurs when an array is partially read or written before the end of array scope. For arrays local to a function, the end of scope occurs when the function ends.

Risk

A partially accessed array often indicates an omission in coding. For instance, when sorting an array using a loop, you used a number of loop iterations such that one array element is never read. The implementation can result in an array that is not fully sorted.

Fix

The fix depends on the root cause of the defect. For instance, if the root cause is a loop with an incorrect number of iterations, change the loop bound or add a step after the loop to access the unread or unwritten elements.

See examples of fixes below.

If you do not want to fix the issue, add comments to your result or code to avoid another review. See:

Examples

expand all

int Calc_Sum(void) 
{
  int tab[5]={0,1,2,3,4},sum=0;  
  /* Defect: tab[4] is not read */ 
  
  for (int i=0; i<4;i++) sum+=tab[i];
  
  return(sum);

 }

The array tab is only partially read before end of function Calc_Sum. While calculating sum, tab[4] is not included.

Correction — Access Every Array Element

One possible correction is to read every element in the array tab.

int Calc_Sum(void) 
{
  int tab[5]={0,1,2,3,4},sum=0;   
  
  /* Fix: Include tab[4] in calculating sum */
  for (int i=0; i<5;i++) sum+=tab[i]; 
  
  return(sum);

 }

Result Information

Group: Data flow
Language: C | C++
Default: On for handwritten code, off for generated code
Command-Line Syntax: PARTIALLY_ACCESSED_ARRAY
Impact: Low

Version History

Introduced in R2013b