/* *kernel : linux2.6.32.63 *file : \scripts\mod\ Modpost.h \scripts\mod\modpost.c *author : davidlin *date : 2014-12-25pm *Email : [email protected] or [email protected] *world : the city of SZ, in China *Ver : 000.000.001 *history : editor time do *          1) linpeng 2014-12-25 created this file!   *          2) */ /* Linux kernel code : modpost.h & modpost.c , author is someone, not me *//* modpost.h */#define nofail (PTR) do_nofail ((PTR), #ptr) void* do_nofail (void* ptr, const char* expr);/* end of modpost.h *//* modpost.c */void* do_nofail (void* ptr, const char* expr) { if (!ptr) fatal ("modpost: memory Allocation failure:%s.\n ", expr);Nbsp; return ptr;} Static struct module* new_module (char* modname) { struct module * mod; char *p, *s; mod = nofail (malloc (*mod)); memset (Mod, 0, sizeof (*mod)); p = nofail (StrDup (modname)); /* strip TRAILING .O */    S = STRRCHR (p, '. '); if (s != null) if (strcmp (s), ". O") == 0) *s = ' /* add to list */ mod->name '; = p; mod->gpl_compatible = -1; mod-> next = Modules; modules = mod; return mod;} /* end of modpost.c */ each individual needs to evolve over and over again, and every engineer is no exception. When it comes to general entry, we might write code like this: Struct module* mod;char *p, *s;mod = malloc (sizeof ( Struct module)); Memset (Mod, 0, sizeof (Struct module));//Not considered mod == Null then went further: Struct module* mod;char *p, *s;mod = malloc (sizeof (struct module ); if (null == mod) return null;memset (mod, 0, sizeof (struct module)); Is it necessary to add a sentence of if (null == ptr) return NULL; is it possible to optimize every time you use the malloc function? Yes, you can! #define nofail (PTR) do_nofail (PTR), #ptr) void* do_nofail ( VOID* PTR, CONST CHAR* EXPR); mod = nofail (malloc (sizeof ( *mod)); memset (Mod, 0, sizeof (*mod)); 1. The non-empty package has been encapsulated in the nofail, not only the coding workReduced, by macro-named self-annotation, it is clear that the malloc expects only success, not failure (of course, just expecting), and can prevent if (null == ptr) accidental omission, but also better debugging and maintenance code; 2. Use sizeof ( *MOD) instead of sizeof (struct module), so that the MoD type changes, does not affect the specific function, to achieve the code adaptive effect. Can you take it further? Can, digestion and absorption, according to the project specific application scenarios, specific things specific optimization.
Linux Kernel Programming: Defensive programming Learning