...
| Code Block | ||||
|---|---|---|---|---|
| ||||
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 | ||||
|---|---|---|---|---|
| ||||
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 Standard | ARR36-CPP. Do not subtract or compare two pointers or iterators that do not refer to the same array or container | ISO/IEC TS 17961 (Draft) | Subtracting or comparing two pointers that do not refer to the same array [ptrobj] |
| MITRE CWE | CWE-469, Use of pointer subtraction to determine size |
...