Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

MISRA.EXPR.SIZEOF.ARRAY_PARAM.2012_AMD1

The sizeof operator shall not have an operand which is a function parameter declared as "array of type"

MISRA C 2012 Rule 12.5: The sizeof operator shall not have an operand which is a function parameter declared as "array of type"

Category: Mandatory

Analysis: Decidable, Single Translation Unit

Applies to: C90, C99

Amplification

The function parameter A in void f ( int32_t A[ 4 ] ) is declared as “array of type”.

Rationale

The sizeof operator can be used to determine the number of elements in an array A:

size_t arraySize = sizeof ( A ) / sizeof ( A[ 0 ] );

This works as expected when A is an identifier that designates an array, as it has type “array of type”. It does not “degenerate” to a pointer and sizeof ( A ) returns the size of the array.

However, this is not the case when A is a function parameter. The Standard states that a function parameter never has type “array of type” and a function parameter declared as an array will “degenerate” to “pointer to type”. This means that sizeof ( A ) is equivalent to sizeof ( int32_t * ), which does not return the size of an array.

Example

int32_t glbA[] = { 1, 2, 3, 4, 5 };

void f ( int32_t A[ 4 ] ) 
{
  /*
   * The following is non-compliant as it always gives the same answer, 
   * irrespective of the number of members that appear to be in the array 
   * (4 in this case), because A has type int32_t * and not int32_t[ 4 ]. 
   * As sizeof ( int32_t * ) is often the same as sizeof ( int32_t ), 
   * numElements is likely to always have the value 1. 
   */ 
  uint32_t numElements = sizeof ( A ) / sizeof ( int32_t );

  /*
   * The following is compliant as numElements_glbA will be given the 
   * expected value of 5. 
   */ 
  uint32_t numElements_glbA = sizeof ( glbA ) / sizeof ( glbA[ 0 ] ); 
}