Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: lite editing, replace camel case, reviewed

...

This noncompliant code example allocates a variable number of objects of type struct obj. The function checks that numObjs num_objs is small enough to prevent wrapping, in compliance with INT30-C. Ensure that unsigned integer operations do not wrap. The size of struct obj is assumed to be 8 bytes to account for padding. However, the padding is dependent on the target architecture as well as compiler settings, so this object size may be incorrect . This would then yield resulting in an incorrect element count.

Code Block
bgColor#FFcccc
#include <stdint.h>
#include <stdio.h>
 
struct obj {
  char c;
  int i;
};
 
void func(FILE *f, struct obj *objs, size_t numObjsnum_objs) {
  const size_t obj_size = 8;
  if (numObjsnum_objs > (SIZE_MAX / obj_size) ||
      numObjsnum_objs != fwrite(objs, obj_size, numObjsnum_objs, f)) {
    /* Handle error */
  }
}

...

This compliant solution uses the sizeof operator to correctly provide the object size and numObjs num_objs to provide the element count.

Code Block
bgColor#ccccff
#include <stdint.h>
#include <stdio.h>
 
struct obj {
  char c;
  int i;
};
 
void func(FILE *f, struct obj *objs, size_t numObjsnum_objs) {
  if (numObjsnum_objs > (SIZE_MAX / sizeof(*objs)) ||
      numObjsnum_objs != fwrite(objs, sizeof(*objs), numObjsnum_objs, f)) {
    /* Handle error */
  }
}

...