...
Code Block | ||
---|---|---|
| ||
#include <string.h> void f4(char p[], const char *q) { const size_t n = sizeof(p); if ((memcpy(p, q, n)) == p) { } } |
This example is also a violation of ARR01-C. Do not apply the sizeof operator to a pointer when taking the size of an array.
Compliant Solution (Two Pointers + One Integer)
...
Code Block | ||
---|---|---|
| ||
#include <stdint.h> #include <stdio.h> struct obj { char c; int i; }; void func(FILE *f, struct obj *objs, size_t numObjs) { const size_t obj_size = 8; if (numObjs > (SIZE_MAX / obj_size) || numObjs != fwrite(objs, 8obj_size, numObjs, f)) { /* Handle error */ } } |
Note that this example is compliant with INT30-C. Ensure that unsigned integer operations do not wrap.
Compliant Solution (One Pointer + Two Integers)
For calls that take a pointer and two integers, generally accept one integer representing the size of an individual object, and a second integer representing the number of objects in the array. The resulting product of the two integers should not be greater than the element count of the pointer were it expressed as an unsigned char *
. See INT30-C. Ensure that unsigned integer operations do not wrap for more information.
Code Block | ||
---|---|---|
| ||
#include <stdint.h> #include <stdio.h> struct obj { char c; int i; }; void func(FILE *f, struct obj *objs, size_t numObjs) { if (numObjs > (SIZE_MAX / sizeof(*objs)) || numObjs != fwrite(objs, sizeof(*objs), numObjs, f)) { /* Handle error */ } } |
...
...