[previous] 2953 [next] Suspicious: Negative value used in array subscript or pointer arithmetic operation.
Arrays

Dataflow analysis has identified a code construct which is suspicious. The code may be entirely safe but further investigation is advisable.

The value of an integer expression is being added to or subtracted from a pointer. Examination of the context indicates that this value will sometimes be negative and dataflow has been unable to determine the dimensions of the object which the pointer may be addressing. Is this intended ? If the original pointer and the resulting pointer do not address elements of the same array or the element one past the end of the array, the result will be invalid.

Notice that this message is not generated when subtracting a positive value from a pointer. It is only generated when adding or subtracting a potentially negative value.

In the following code example, the value ('x') being added to the pointer ('p') will be negative unless the value of parameter 'n' is greater than 0.


/*PRQA S 488,491,492,506,510,2017,2211,2824,2984,2986,3120,3132,3198,3199,3203,3227,3408,3447,3673,3690 ++*/

void foo(int *p, int n)
{
   int  x = -1;
   int  i;

   for (i = 0; i < n; ++i)
   {
      x++;
   }


   p[x] = 0;               /* 2953 */

   *(p + x) = 0;           /* 2953 */
}

See also:

QA·C Source Code Analyser 8.1.2
© 2013 Programming Research.
www.programmingresearch.com
Personality Groups | Glossary | Message Index Contents