From b178d0792b6335277f7fa831fd7e5403105abd04 Mon Sep 17 00:00:00 2001 From: Timo Sirainen Date: Tue, 28 Sep 2021 01:24:24 +0300 Subject: [PATCH] lib: container_of() - Always return NULL if input pointer is NULL --- src/lib/macros.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/lib/macros.h b/src/lib/macros.h index fb5923dc3c..3a3db2c3ed 100644 --- a/src/lib/macros.h +++ b/src/lib/macros.h @@ -26,9 +26,15 @@ #define CONST_PTR_OFFSET(ptr, offset) \ ((const void *) (((uintptr_t) (ptr)) + ((size_t) (offset)))) +static inline const char *container_of_ptr(const void *ptr, size_t offset) +{ + if (ptr == NULL) + return NULL; + return (const char *)ptr - offset; +} #define container_of(ptr, type, name) \ - (type *)((char *)(ptr) - offsetof(type, name) + \ - COMPILE_ERROR_IF_TYPES_NOT_COMPATIBLE(ptr, &((type *) 0)->name)) + (type *)(container_of_ptr(ptr, offsetof(type, name) + \ + COMPILE_ERROR_IF_TYPES_NOT_COMPATIBLE(ptr, &((type *) 0)->name))) /* Don't use simply MIN/MAX, as they're often defined elsewhere in include files that are included after this file generating tons of warnings. */ -- 2.47.3