Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

283
Views
Initializing an atomic flag in a malloc'd structure

I'm trying to use atomics in C on FreeBSD 10.1 Release with clang 3.6.1, however when I try to compile a program using ATOMIC_FLAG_INIT on a atomic_flag variable in a struct I get error: expected expression.

Here is the program I am trying to compile.

#include <stdio.h>
#include <stdatomic.h>

struct map
{

    atomic_flag flag;

};

int main(void)
{
    struct map *m = malloc(sizeof(struct map));

    m->flag = ATOMIC_FLAG_INIT;

    free(m);

    return 0;
}

I can use atomic_flag outside of structs like in the example below but not in structs, so how do you use atomic variables in C structs?

#include <stdio.h>
#include <stdatomic.h>

int main(void)
{
    atomic_flag flag = ATOMIC_FLAG_INIT;

    return 0;
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

atomic_flag doesn't have value that you can assign to or read from, but only an internal state.

The only way to interact with atomic_flag are the two functions (or four if you count the _explicit versions) that are defined for it. For your case when you got your object through malloc the flag is in an "indeterminate state" (7.17.8 p4 of C11). You can simply put it into a known state by applying one of the two functions, that is use atomic_flag_clear to set it to the "clear" state, or use atomic_flag_test_and_set to set it to the "set" state.

Using atomic_flag_clear right after an allocation with malloc is equivalent to an initialization of a variable with ATOMIC_FLAG_INIT.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!