</>EmbeddedInterview
← All problems · Pointers & Strings

Implement container_of

Medium

Linux and most RTOS kernels embed list nodes inside the structures they link. Given a pointer to the embedded member, you need the address of the structure that contains it.

  1. Implement the macro container_of(ptr, type, member).
  2. Use it in struct sensor *sensor_from_node(struct list_node *n).
struct list_node { struct list_node *next; };
struct sensor { int id; char name[12]; struct list_node node; float value; };

Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

offsetof(type, member) from <stddef.h> gives the member's byte offset inside the structure. Convert the member pointer to char * so the subtraction is in bytes, subtract the offset, and cast to type *.

#include <stdio.h>
#include <stddef.h>

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

struct list_node { struct list_node *next; };
struct sensor { int id; char name[12]; struct list_node node; float value; };

struct sensor *sensor_from_node(struct list_node *n)
{
    return n ? container_of(n, struct sensor, node) : NULL;
}

Your macro is correct and identical to the classic definition. It needs #include <stddef.h> for offsetof.

How it works: a member lives at a fixed byte offset from the start of its structure. If &s.node is address A and offsetof(struct sensor, node) is 16, the structure starts at A − 16.

Example layout on a 64-bit machine

member offset size
id 0 4
name[12] 4 12
node 16 8
value 24 4

Given ptr = 0x1010 for node, the macro computes 0x1010 − 16 = 0x1000, the address of the struct sensor.

Why the (char *) cast is essential: pointer arithmetic is scaled by the pointed-to type. ptr - 16 on a struct list_node * would move back 16 × 8 bytes. Casting to char * makes the subtraction count single bytes.

Why kernels use it: the list code works only with struct list_node, so one generic list implementation serves every structure, nodes need no separate allocation, and one object can sit on several lists through several embedded nodes. Linux's list_head, rb_node, kobjects and almost every driver's private data (container_of(inode->i_cdev, struct my_dev, cdev)) rely on it.

The Linux version adds type checking: it rejects a ptr whose type does not match member, using static_assert with __same_type() (older kernels used a GCC statement expression with typeof). The plain version above silently accepts a wrong pointer and returns garbage.

Follow-up: the classic way to implement offsetof itself is ((size_t)&((type *)0)->member). Technically it is undefined behaviour, because it dereferences a null pointer, which is why compilers provide __builtin_offsetof and you should use the standard macro.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
struct pair { char tag; double d; int first; };
int main(void)
{
    struct sensor s[2] = { { 1, "temp", { NULL }, 21.5f }, { 2, "humidity", { NULL }, 40.0f } };
    s[0].node.next = &s[1].node;

    CHECK(sensor_from_node(&s[0].node) == &s[0]);
    CHECK(sensor_from_node(s[0].node.next) == &s[1]);
    CHECK(sensor_from_node(s[0].node.next)->id == 2);

    int sum = 0;                                    /* walk the list */
    for (struct list_node *p = &s[0].node; p; p = p->next)
        sum += sensor_from_node(p)->id;
    CHECK(sum == 3);

    struct pair pr;
    CHECK(container_of(&pr.first, struct pair, first) == &pr);  /* member not first, padding */
    CHECK(container_of(&pr.tag, struct pair, tag) == &pr);      /* member at offset 0 */
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}