Skip to content

Instantly share code, notes, and snippets.

@Hypro999
Last active March 30, 2022 18:24
Show Gist options
  • Save Hypro999/01c56c4810dd49b9c865bea8c0df3751 to your computer and use it in GitHub Desktop.
Save Hypro999/01c56c4810dd49b9c865bea8c0df3751 to your computer and use it in GitHub Desktop.
Adapted snippet from the Linux source code demonstrating the use of GCC statement expressions to implement intrusive linked lists in C.
#include <stdio.h>
#include <stdlib.h>
#define container_of(type, ptr, member) \
({ \
size_t offset = (size_t)&(((type *)0)->member); \
char *start_addr = (char *)(ptr) - offset; \
(type *)start_addr; \
})
struct list {
struct list *prev;
struct list *next;
};
struct device {
int id;
struct list list;
};
struct device *new_device(int id) {
struct device *dev = (struct device *)malloc(sizeof(struct device));
if (dev == NULL) {
fprintf(stderr, "failed to allocate memory");
exit(EXIT_FAILURE);
}
dev->id = id;
dev->list.prev = NULL;
dev->list.next = NULL;
return dev;
}
int main() {
struct device *head = new_device(1);
struct device *ptr = container_of(struct device, &(head->list), list);
printf("addresses: %p %p\n", head, ptr);
free(head);
head = NULL;
ptr = NULL;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment