Versions Compared

Key

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

...

Wiki Markup
The problem with this code is that the {{flexArrayStruct}} does not actually reserve space for the integer array data:; Itit can't because the size hasn't been specified. Consequently, while 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 bounds.

Compliant

...

Solution (Storage Allocation)

This compliant solution dynamically allocates storage for struct flexArrayStruct.

...

The problem with this noncompliant code example is that 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.

Compliant Solution (Copying)

...

Code Block
bgColor#ccccff
struct flexArrayStruct *flexStructA;
struct flexArrayStruct *flexStructB;
size_t array_size;
size_t i;

/* Initialize array_size */

/* Allocate memory for flexStructA */

/* Allocate memory for flexStructB */

/* Initialize flexStructA */

/* ... */

memcpy(
  flexStructB, 
  flexStructA, 
  (sizeof(struct flexArrayStruct) + sizeof(int) * array_size)
);

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

...

Flexible array structs should not be

  • declared on the stack: They , they should be on the heap.
  • copied via assignment: They , they should be copied using memcpy() or a similar function.
  • passed as raw arguments to functions; A , a pointer should be passed to flexArrayStruct intead.

...