CERT-ARR38-C_f
Synopsis
Guarantee that library functions do not form invalid pointers.
Enabled by default
Yes
Severity/Certainty
High/High

Full description
C library functions that make changes to arrays or objects take at least two arguments: a pointer to the array or object and an integer indicating the number of elements or bytes to be manipulated. Supplying arguments to such a function might cause the function to form a pointer that does not point into or just past the end of the object, resulting in undefined behavior.
Coding standards
- CERT ARR38-C
Guarantee that library functions do not form invalid pointers
- CWE 121
Stack-based Buffer Overflow
- CWE 119
Improper Restriction of Operations within the Bounds of a Memory Buffer
- CWE 125
Out-of-bounds Read
- CWE 123
Write-what-where Condition
- CWE 805
Buffer Access with Incorrect Length Value
- CWE 129
Improper Validation of Array Index
Code examples
The following code example fails the check and will give a warning:
#include<stdlib.h>
int example(unsigned char *s) {
unsigned char *p = s, *pl;
unsigned short hbtype;
unsigned int payload;
unsigned int padding = 16; /* Use minimum padding */
unsigned char *buffer, *bp;
int r;
/* Read type and payload length first */
hbtype = *p++;
payload = *((unsigned int *)p++);
pl = p;
buffer = malloc(1 + 2 + payload + padding);
bp = buffer;
memcpy(bp, pl, payload);
}
The following code example passes the check and will not give a warning about this issue:
#include<stdlib.h>
int example(unsigned char *s, unsigned int length) {
unsigned char *p = s, *pl;
unsigned short hbtype;
unsigned int payload;
unsigned int padding = 16; /* Use minimum padding */
unsigned char *buffer, *bp;
int r;
/* Read type and payload length first */
hbtype = *p++;
payload = *((unsigned int *)p++);
if (1 + 2 + payload + 16 > length)
return 0;
pl = p;
buffer = malloc(1 + 2 + payload + padding);
bp = buffer;
memcpy(bp, pl, payload);
}