[sr-dev] git:master: core: use offsetof() extension to finding the memory offset of a member of a structure

Marius Zbihlei marius.zbihlei at 1and1.ro
Tue Aug 17 10:26:14 CEST 2010


Module: sip-router
Branch: master
Commit: b23832622f9211a04b1718741fd46eabb41937d5
URL:    http://git.sip-router.org/cgi-bin/gitweb.cgi/sip-router/?a=commit;h=b23832622f9211a04b1718741fd46eabb41937d5

Author: Marius Zbihlei <marius.zbihlei at 1and1.ro>
Committer: Marius Zbihlei <marius.zbihlei at 1and1.ro>
Date:   Tue Aug 17 11:12:38 2010 +0300

core: use offsetof() extension to finding the memory offset of a member of a structure

This replaces some undefined behavior code in the form of null pointer dereferences
Offsetof is present in stddef.h and it is fairly portable across platforms/compilers.

---

 sr_module.c |    7 ++++---
 1 files changed, 4 insertions(+), 3 deletions(-)

diff --git a/sr_module.c b/sr_module.c
index 9c7a2a9..e4f94a3 100644
--- a/sr_module.c
+++ b/sr_module.c
@@ -69,6 +69,7 @@
 #include <strings.h>
 #include <stdlib.h>
 #include <string.h>
+#include <stddef.h> /* for offsetof */
 
 
 struct sr_module* modules=0;
@@ -922,9 +923,9 @@ int init_modules(void)
 action_u_t *fixup_get_param(void **cur_param, int cur_param_no,
 							int required_param_no)
 {
-	action_u_t *a, a2;
+	action_u_t *a;
 	/* cur_param points to a->u.string, get pointer to a */
-	a = (void*) ((char *)cur_param - ((char *)&a2.u.string-(char *)&a2));
+	a = (void*) ((char *)cur_param - offsetof(action_u_t, u.string));
 	return a + required_param_no - cur_param_no;
 }
 
@@ -947,7 +948,7 @@ int fixup_get_param_count(void **cur_param, int cur_param_no)
 action_param_type* fixup_get_param_ptype(void** param)
 {
 	action_u_t* a;
-	a = (void*)((char*)param - (char*)&(((action_u_t*)(0))->u.string));
+	a = (void*)((char*)param - offsetof(action_u_t, u.string));
 	return &a->type;
 }
 




More information about the sr-dev mailing list