Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edits; reviewed

The C Standard provides flexible array members in the C language. While flexible array members are useful, they need to be understood and used with care, subclause 6.7.2.1 paragraph 18, says:

As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply.

The following is an example of a structure that contains a flexible array member:

...

This definition means that when allocating storage, only the first member, num, is considered. Consequently, the result of accessing the member data of a variable of type non-pointer type struct flexArrayStruct is undefined. DCL38-C. Use the correct syntax when declaring flexible array members describes the correct way to declare a struct with a flexible array member.

To avoid the potential for undefined behavior, structures that contain a flexible array member should always be allocated and operated on dynamically. Flexible array structures should not be:

  • have allocated storage duration (be allocated via malloc(), or another dynamic allocation function)
  • be dynamically
  • declared on the stack; they should be on the heap.
  • copied via assignment; they should be copied using memcpy(), or a similar function.
  • passed as raw arguments to functions; should be passed as a pointer instead.to functions

Noncompliant Code Example (Storage

...

Duration)

This noncompliant code example statically allocates uses automatic storage for a structure containing a flexible array member:

Code Block
bgColor#FFcccc
langc
#include <stddef.h>
 
struct flexArrayStruct {
  intsize_t num;
  int data[];
};
 
void func(void) {
  struct flexArrayStruct flexStruct;
  size_t array_size = 4;

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

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

The problem with this code is that the flexArrayStruct does not actually reserve space for the integer array data; it can't because the size is not specified. Consequently, although initializing the num member to zero is allowed, attempting to write even one value into data (that is, data[0]) is likely to overwrite memory outside of the object's boundsBecause flexStruct does not use allocated memory, no space is reserved for the data member.  Accessing the data member is undefined behavior.

Compliant Solution (Storage

...

Duration)

This compliant solution dynamically allocates storage for struct flexArrayStruct:

Code Block
bgColor#ccccff
langc
#include <stdlib.h>
 
struct flexArrayStruct {
  intsize_t num;
  int data[];
};
 
void func(void) {
  struct flexArrayStruct *flexStruct;
  size_t array_size = 4;

  /* Dynamically allocate memory for the structure. */
  flexStruct = (struct flexArrayStruct *)malloc(
    sizeof(struct flexArrayStruct) + sizeof(int) * array_size);
  if (flexStruct == NULL) {
    /* Handle error */
  }

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

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

...

Noncompliant Code Example (Copying)

...

Code Block
bgColor#FFcccc
langc
#include <stddef.h>
 
struct flexArrayStruct {
  intsize_t num;
  int data[];
};
 
void func(struct flexArrayStruct *structA,
          struct flexArrayStruct *structB) {
  *flexStructB = *flexStructA;
}

The problem with this noncompliant code example is that when When the structure is copied, the size of the flexible array member is not considered, and only the first member of the structure, num, is copied, leaving the array contents untouched.

Compliant Solution (Copying)

...

Code Block
bgColor#ccccff
langc
#include <string.h>
 
struct flexArrayStruct {
  intsize_t num;
  int data[];
};
 
void func(struct flexArrayStruct *structA,
          struct flexArrayStruct *structB) {
  if (structA->num > structB->num) {
    /* Insufficient space; Handle error */
    return;
  }
  memcpy(structB, structA,
         sizeof(struct flexArrayStruct) + (sizeof(int)
           * array_sizestructA->num));
}

This compliant solution ensures that the entire structure, including the flexible array member, is copied correctly.

Noncompliant Code Example (Function Arguments)

In this noncompliant code example, the flexible array structure is passed directly to a function that tries to print prints the array elements:

Code Block
bgColor#FFcccc
langc
#include <stdio.h>
#include <stdlib.h>
 
struct flexArrayStruct {
  intsize_t num;
  int data[];
};
 
void print_array(struct flexArrayStruct structP) {
  puts("Array is: ");
  for (size_t i = 0; i < structP.num; i++i) {
    printf("%d", structP.data[i]);
  }
  puts("\n");
}

void func(void) {
  struct flexArrayStruct *structP;
  size_t array_size = 4;

  /* Space is allocated for the struct. */
  structP = (struct flexArrayStruct *)malloc(
    sizeof(struct flexArrayStruct) + sizeof(int) * array_size);
  if (structP == NULL) {
    /* Handle error */
  }
  structP->num = array_size;

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

Because C passes the argument by value, the structure is copied onto the stack. The size of the flexible array member is not considered when the structure is copied, and only the first member of the structure, num, is copied.

...

Code Block
bgColor#ccccff
langc
#include <stdio.h>
#include <stdlib.h>
 
struct flexArrayStruct {
  intsize_t num;
  int data[];
};
 
void print_array(struct flexArrayStruct *structP) {
  puts("Array is: ");
  for (size_t i = 0; i < structP->num; i++i) {
    printf("%d", structP->data[i]);
  }
  puts("\n");
}
 
void func(void) {
  struct flexArrayStruct *structP;
  size_t array_size = 4;

  /* Space is allocated for the struct. */
  structP = (struct flexArrayStruct *)malloc(
    sizeof(struct flexArrayStruct) + sizeof(int) * array_size);
  if (structP == NULL) {
    /* Handle error */
  }
  structP->num = array_size;

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

...