Skip to main content

IAR Embedded Workbench for RL78 5.20

CERT-MEM33-C_b

In this section:
Synopsis

Allocate and copy structures containing a flexible array member dynamically.

Enabled by default

Yes

Severity/Certainty

Low/Low

lowlow.png
Full description

Unless the appropriate size of the flexible array member has been explicitly added when allocating storage for an object of the struct, the result of accessing the member data of a variable of non-pointer type struct flex_array_struct is undefined. To avoid the potential for undefined behavior, structures that contain a flexible array member should always be allocated dynamically.

Coding standards
CERT MEM33-C

Allocate and copy structures containing flexible array members dynamically

Code examples

The following code example fails the check and will give a warning:

#include <stddef.h>

struct flex_array_struct {
  size_t num;
  int data[];
};

void func(struct flex_array_struct *struct_a,
          struct flex_array_struct *struct_b) {
  *struct_b = *struct_a;
}

The following code example passes the check and will not give a warning about this issue:

#include <string.h>

struct flex_array_struct {
  size_t num;
  int data[];
};

void func(struct flex_array_struct *struct_a,
          struct flex_array_struct *struct_b) {
  if (struct_a->num > struct_b->num) {
    /* Insufficient space; handle error */
    return;
  }
  memcpy(struct_b, struct_a,
         sizeof(struct flex_array_struct) + (sizeof(int)
           * struct_a->num));
}