Main Content

MISRA C:2012 Rule 12.6

Structure and union members of atomic objects shall not be directly accessed

Since R2025a

Description

Rule Definition

Structure and union members of atomic objects shall not be directly accessed.1

Rationale

The C standard specifies that data races must not occur when performing atomic operations on objects that are shared between threads even when you do not explicitly protect them using mutexes or condition variables. Directly accessing structures and union members of atomic objects instead of using access functions provided in the C standard can result in unexpected data races.

When accessing atomic objects of union or structure types, access the object as a whole. Use the assignment operator (=) and these access functions provided by the C standard:

  • atomic_init()

  • atomic_store()

  • atomic_load()

  • atomic_exchange()

  • atomic_compare_exchange()

Avoid accessing members of atomic structures and unions by using the dot (.) or arrow (->) operator.

Polyspace Implementation

Polyspace® reports a violation if you use the dot (.) or arrow (->) operator to access a member of an atomic structure or an atomic union.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

In this example, the structure msVar is an atomic structure. The function foo() accesses the structure member msVar.num2 directly by using the dot operator. Polyspace reports a violation. The function bar() shows the compliant method for setting a member of an atomic structure using access functions from the C11 standard.

 #include <stdint.h>
#include <stdatomic.h>

typedef struct myStruct {
	uint8_t num1;
	uint8_t num2;
} myStruct;

_Atomic myStruct msVar;

void foo() {
	msVar.num2 = 42U;  //Noncompliant
}

void bar() {
	myStruct temp = {0U, 0U};
	temp = atomic_load(&msVar); //Compliant
	temp.num2 = 43U;
	atomic_store(&msVar, temp); //Compliant
}

Check Information

Group: Expressions
Category: Required
AGC Category: Required

Version History

Introduced in R2025a


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.