Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Noncompliant Code Example

Prior to the introduction of flexible array members in the C99 standard, structures with a one element array as the final member were used to achieve similar functionality. This noncompliant code example illustrates how struct flexArrayStruct is declared in this case.

This noncompliant code attempts to allocated a flexible array member with a one element array as the final member. When the structure In this noncompliant code, an array of size 1 is declared, but when the structure itself is instantiated, the size computed for malloc() is modified to account for the actual size of the dynamic array.

Code Block
bgColor#FFcccc
struct flexArrayStruct {
  int num;
  int data[1];
};

/* ... */

size_t array_size;
size_t i;

/* initialize array_size */

/* space is allocated for the struct */
struct flexArrayStruct *structP
  = (struct flexArrayStruct *)
     malloc(sizeof(struct flexArrayStruct)
          + sizeof(int) * (array_size - 1));
if (structP == NULL) {
  /* Handle malloc failure */
}
structP->num = 0;

/* access data[] as if it had been allocated
 * as data[array_size] */
for (i = 0; i < array_size; i++) {
  structP->data[i] = 1;
}

Wiki MarkupThe problem with using this code approach is that the only member that is guaranteed to be valid, by strict C99 definition, is {{structP->data\[0\]}}. Consequently, for all {{i > 0}}, the results of the assignment are undefined.

Implementation Details

the behavior is undefined when accessing other than the first element of data (see Section 6.5.6, Paragraph 8 of the C99 standard). Consequently, the compiler can generate code that does not return the expected value when accessing the second element of data.

This approach The noncompliant example may be the only alternative for compilers that do not yet implement the C99 syntax. Microsoft Visual Studio 2005 does not implement the C99 syntax.

...