</>EmbeddedInterview

What are offsetof and container_of?

MediumPointers & Memory

Short answer: offsetof(type, member) (from <stddef.h>) gives the byte offset of a member within a struct, as a compile-time constant. container_of(ptr, type, member) (a Linux kernel macro) uses it the other way round: given a pointer to a member, it computes the address of the struct that contains it. Together they let generic code (lists, queues, callbacks) work with embedded "hook" members.

#include <stddef.h>
#include <stdint.h>

#define container_of(ptr, type, member) \
    ((type *)((char *)(ptr) - offsetof(type, member)))

struct list_node { struct list_node *next; };

struct uart_msg {
    uint8_t len;
    uint8_t data[16];
    struct list_node node;          /* hook used by a generic queue */
};

void process(struct list_node *n)
{
    struct uart_msg *m = container_of(n, struct uart_msg, node);
    /* m->len, m->data are now accessible */
}

How offsetof can be implemented (the classic version, technically undefined but historically common):

#define my_offsetof(type, member) ((size_t)&(((type *)0)->member))

Modern compilers provide __builtin_offsetof, which <stddef.h> uses; always use the standard macro.

Uses

  • Intrusive linked lists (Linux list_head, Zephyr sys_slist, FreeRTOS list items inside the TCB): the list code only knows about the node; container_of gets back to the object. No separate allocation per list entry.
  • Callbacks with embedded context: a driver registers a struct timer embedded in its own state struct; the timer callback receives struct timer * and recovers the driver state.
  • Checking layouts: _Static_assert(offsetof(struct regs, CTRL) == 0x08, "") to verify that a register struct matches the datasheet.
  • Serialisation code that needs member positions.

Cautions: container_of is only correct if the pointer really points to that member of that type of struct; a wrong type gives a silently wrong address. The kernel's version adds a type check using typeof to catch mismatches at compile time.