Versions Compared

Key

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

...

Code Block
bgColor#ccccff
langc
#include <threads.h>
 
struct multi_threaded_flags {
  unsigned int flag1 : 2;
  unsigned int flag2 : 2;
};

union mtf_protect {
  struct multi_threaded_flags s;
  long padding;
};

static_assert(sizeof(long) >=
              sizeof(struct multi_threaded_flags));

struct mtf_mutex {
  union mtf_protect u;
  mtx_t mutex;
};

struct mtf_mutex flags;

void thread1(void) {
  int result;
  if ((result = mtx_lock(&flags.mutex)) == thrd_error) {
    /* Handle error */
  }
  flags.u.s.flag1 = 1;
  if ((result = mtx_unlock(&flags.mutex)) == thrd_error) {
    /* Handle error */
  }
}

void thread2(void) {
  int result;
  if ((result = mtx_lock(&flags.mutex)) == thrd_error) {
    /* Handle error */
  }
  flags.u.s.flag2 = 2;
  if ((result = mtx_unlock(&flags.mutex)) == thrd_error) {
    /* Handle error */
  }
}

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Bibliography

[ISO/IEC 9899:2011]Section 3.14, "Memory Location"

...