Linux核心編程:防禦性編程學習

來源:互聯網
上載者:User

標籤:linux kernel

/* *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);    return ptr;}static struct module* new_module(char* modname){    struct module* mod;    char *p, *s;        mod = NOFAIL(malloc(sizeof(*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 = ‘\0‘;    /* add to list */    mod->name = p;    mod->gpl_compatible = -1;    mod->next = modules;    modules = mod;    return mod;}/* end of modpost.c */ 每個個體都需要重複演化,每個工程師也不例外。一般入門的時候,我們可能如下編寫代碼:開始如同這步:struct module* mod;char *p, *s;mod = malloc(sizeof(struct module));memset(mod, 0, sizeof(struct module));//未考慮mod == NULL於是更進一步:struct module* mod;char *p, *s;mod = malloc(sizeof(struct module));if(NULL == mod) return NULL;memset(mod, 0, sizeof(struct module));如何再進一步?是否每次使用malloc函數,都需要增加一句 if(NULL == ptr) return NULL;是否可以最佳化? 是的,可以!#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.非空封裝已經封裝在NOFAIL中,不僅編碼工作減少,通過宏命名的自注釋,可以很清楚知道該malloc期望的是只許成功,不許失敗(當然只是期待),而且可以防止if(NULL == ptr)的偶然遺漏,更可更好的調試及維護代碼;2.使用sizeof(*mod)代替sizeof(struct module),使得mod類型變更時,並不會影響到具體函數,達到代碼自適應效果。還可以更進一步?可以,消化吸收,根據項目具體應用情景,具體事物具體最佳化。

Linux核心編程:防禦性編程學習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.