Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: ref MSC21-C

...

In this noncompliant code example, the function find() attempts to iterate over the elements of the flexible array member buf, starting with the second element. However, because function g() does not allocate any storage for the member, the expression first++ in find() attempts to form a pointer just past the end of buf when there are no elements. This attempt results in undefined behavior 62. See MSC21-C. Use robust loop termination conditions for more information.

Code Block
bgColor#ffcccc
langc
#include <stdlib.h>
 
struct S {
  size_t len;
  char buf[];  /* Flexible array member */
};

const char *find(const struct S *s, int c) {
  const char *first = s->buf;
  const char *last  = s->buf + s->len;

  while (first++ != last) { /* Undefined behavior */
    if (*first == (unsigned char)c) {
      return first;
    }
  }
  return NULL;
}
 
void g(void) {
  struct S *s = (struct S *)malloc(sizeof(struct S));
  if (s == NULL) {
    /* handle error */
  }
  s->len = 0;
  find(s, 'a');
}

...