β

Do Use CALLOC(2)!

./Lu 2 阅读

A struct should always be zeroed out when being initialized, otherwise its members may contain arbitrary data which makes branching according to its member unreliable.

Consider the code below:

tokp = malloc(sizeof(tok_t));

if (tokp->type != NULL)
    switch(tokp->type) {
        case tok_id:
            break;
        case tok_num:
            break;
        default:
            break;
    }

tokp->type should be either NULL or tok_id or tok_num in the context, but if the struct isn’t zeroed out, the branch default may be executed because tokp->type contains rubbish thus is not NULL .

calloc(2) is preferred when initializing a struct, it combines malloc(1) and memset(3) .

作者:./Lu
Better now than later.Better late than never.
原文地址:Do Use CALLOC(2)!, 感谢原作者分享。

发表评论