Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: changed strings to c_str and removed the obsolete reference to 17961

...

Code Block
bgColor#ffcccc
langc
int nums[SIZE];
char *stringsc_str[SIZE];
int *next_num_ptr = nums;
int free_bytes;

/* increment next_num_ptr as array fills */

free_bytes = stringsc_str - (char **)next_num_ptr;

The first incorrect assumption is that the nums and strings c_str arrays are necessarily contiguous in memory. The second is that free_bytes is the number of bytes available. The subtraction returns the number of elements between next_num_ptr and strings c_str.

Compliant Solution

In this compliant solution, the number of free elements is kept as a counter and adjusted on every array operation. It is also calculated in terms of free elements instead of bytes. This practice prevents further mathematical errors.

Code Block
bgColor#ccccff
langc
int nums[SIZE];
char *stringsc_str[SIZE];
int *next_num_ptr = nums;
int free_bytes;

/* increment next_num_ptr as array fills */

free_bytes = (&(nums[SIZE]) - next_num_ptr) * sizeof(int);

...

CERT C++ Secure Coding StandardARR36-CPP. Do not subtract or compare two pointers or iterators that do not refer to the same array or containerISO/IEC TS 17961 (Draft)Subtracting or comparing two pointers that do not refer to the same array [ptrobj]
MITRE CWECWE-469, Use of pointer subtraction to determine size

...