Skip to main content

IAR Embedded Workbench for RH850 3.20.x

CERT-MEM33-C_a

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(void) {
  struct flex_array_struct flex_struct;
  size_t array_size = 4;

  /* Initialize structure */
  flex_struct.num = array_size;

  for (size_t i = 0; i < array_size; ++i) {
    flex_struct.data[i] = 0;
  }
}

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

#include <stdlib.h>

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

void func(void) {
  struct flex_array_struct *flex_struct;
  size_t array_size = 4;

  /* Dynamically allocate memory for the struct */
  flex_struct = (struct flex_array_struct *)malloc(
    sizeof(struct flex_array_struct)
    + sizeof(int) * array_size);
  if (flex_struct == NULL) {
    /* Handle error */
  }

  /* Initialize structure */
  flex_struct->num = array_size;

  for (size_t i = 0; i < array_size; ++i) {
    flex_struct->data[i] = 0;
  }
}