[ccan] why add the result of check_type in container_of

Yubin Ruan ablacktshirt at gmail.com
Mon Mar 12 14:19:39 AEDT 2018


Hi,

I notice that in the implementation of container_of(), the resulting pointer
will be advanced by 1 if types mismatch:

#define container_of(member_ptr, containing_type, member)   \
	 ((containing_type *)                                   \
	  ((char *)(member_ptr)                                 \
	   - container_off(containing_type, member))            \
	  + check_types_match(*(member_ptr), ((containing_type *)0)->member))

where check_types_match() is defined as 

#define check_types_match(expr1, expr2)		\
	((typeof(expr1) *)0 != (typeof(expr2) *)0)

which will return 1 if types mismatch.

IMO, advancing the wrong pointer (resulting from mismatch types) by 1 will
only make things worse, and users usually only get garbage results and will not
be aware of the type-mismatch bug. Wouldn't it be better to throw an building
error/warning for that?

Yubin


More information about the ccan mailing list