</>EmbeddedInterview

Implement a reference counter for a shared object.

Medium"Coding: Concurrency Primitives"
#include <stdatomic.h>
#include <stdlib.h>

typedef struct buffer {
    atomic_uint refs;
    size_t len;
    unsigned char data[];
} buffer_t;

buffer_t *buf_new(size_t len)
{
    buffer_t *b = malloc(sizeof *b + len);
    if (b) { atomic_init(&b->refs, 1u); b->len = len; }     /* creator holds one reference */
    return b;
}

buffer_t *buf_get(buffer_t *b)                               /* take an extra reference */
{
    atomic_fetch_add_explicit(&b->refs, 1u, memory_order_relaxed);
    return b;
}

void buf_put(buffer_t *b)                                    /* drop a reference */
{
    if (atomic_fetch_sub_explicit(&b->refs, 1u, memory_order_release) == 1u) {
        atomic_thread_fence(memory_order_acquire);           /* see all writes made before other puts */
        free(b);                                             /* last reference: destroy */
    }
}

Points: increment can be relaxed (you already hold a reference, so the object cannot disappear); the decrement uses release, and the thread that drops the last reference uses an acquire fence before freeing, so it sees every other thread's writes. Guard against overflow in long-running systems (the Linux kernel's refcount_t saturates instead of wrapping, which turns use-after-free bugs into leaks). You may only get a reference from an object you already hold a reference to; looking an object up in a shared table and taking a reference needs the table's lock (or refcount_inc_not_zero with RCU).