CERT-ARR30-C_j
Synopsis
Do not form or use out-of-bounds pointers or array subscripts.
Enabled by default
Yes
Severity/Certainty
High/High

Full description
Invalid pointer operations could lead to undefined behavior. These include forming an out-of-bounds pointer or array index, dereferencing a past-the-end pointer or array index, accessing or generating a pointer past flexible array member, and null pointer arithmetic.
Coding standards
- CERT ARR30-C
Do not form or use out of bounds pointers or array subscripts
- CWE 119
Improper Restriction of Operations within the Bounds of a Memory Buffer
- CWE 120
Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
- CWE 121
Stack-based Buffer Overflow
- CWE 123
Write-what-where Condition
- CWE 124
Buffer Underwrite ('Buffer Underflow')
- CWE 126
Buffer Over-read
- CWE 127
Buffer Under-read
- CWE 129
Improper Validation of Array Index
- CWE 786
Access of Memory Location Before Start of Buffer
Code examples
The following code example fails the check and will give a warning:
#include <string.h>
#include <stdlib.h>
char *init_block(size_t block_size, size_t offset,
char *data, size_t data_size) {
char *buffer = malloc(block_size);
if (data_size > block_size || block_size - data_size < offset) {
/* Data won't fit in buffer, handle error */
}
memcpy(buffer + offset, data, data_size);
return buffer;
}
The following code example passes the check and will not give a warning about this issue:
#include <string.h>
#include <stdlib.h>
char *init_block(size_t block_size, size_t offset,
char *data, size_t data_size) {
char *buffer = malloc(block_size);
if (NULL == buffer) {
/* Handle error */
exit(0);
}
if (data_size > block_size || block_size - data_size < offset) {
/* Data won't fit in buffer, handle error */
}
memcpy(buffer + offset, data, data_size);
return buffer;
}