Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Avoid unsigned wrapping in compliant solution.

...

This compliant solution ensures the size argument used to allocate vla is in a valid range (between 1 and a programmer-defined maximum); otherwise, it uses an algorithm that relies on dynamic memory allocation:.  The solution also avoids unsigned integer wrapping that, given a sufficiently large value of size, would cause malloc to allocate insufficient storage for the array.

Code Block
bgColor#ccccff
langc
#include <stdint.h>
#include <stdlib.h>
 
enum { MAX_ARRAY = 1024 };
extern void do_work(int *array, size_t size);
 
void func(size_t size) {
  if (0 == size || SIZE_MAX / sizeof(int) < size && ) {
    /* Handle error */
    return;
  }
  if (size < MAX_ARRAY) {
    int vla[size];
    do_work(vla, size);
  } else {
    int *array = (int *)malloc(size * sizeof(int));
    if (array == NULL) {
      /* Handle error */
    }
    do_work(array, size);
    free(array);
  }
}

...