/* *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, inch *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_n Ofail (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); 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;
Each individual needs to evolve over and over again, and every engineer is no exception. As a general introduction, we might write code like this:
Begin as this step:
struct module* Mod;char *p, *s;mod = malloc (sizeof (struct module)), memset (mod, 0, sizeof (struct module))//not considered mod = = NULL
Thus further:
struct module* Mod;char *p, *s;mod = malloc (sizeof (struct module)), if (NULL = = MoD) return null;memset (mod, 0, sizeof (struc T module));
How to go further?
Each time you use the malloc function, you need to add an if (null = = PTR) return null;
Is it possible to optimize? Yes, I can!
#define NOFAIL (PTR) do_nofail (PTR), #ptr) void* do_nofail (void* ptr, const char* expr); MoD = NOFAIL (malloc (*mod)); memset (mod, 0, sizeof (*MOD));
1. The non-empty package has been encapsulated in the nofail, not only the coding work is reduced, by the macro-named self-annotation, it is clear to know that malloc is expected to only succeed, not to fail (of course, just expecting), and can prevent if (NULL = = ptr) Accidental omission, Better debugging and maintenance of 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