【发布时间】:2020-02-18 10:55:23
【问题描述】:
这样使用安全吗,使用gcc 4.9.2编译的代码没有任何错误或警告
widget *p;
...
p = malloc(sizeof *p);
我在 SEI CERT C 编码标准 网站上找到了这个。
点击here -- 没有类型不匹配的问题,不需要强制转换。您每次都分配适量的内存。
struct widget;
typedef struct widget widget_t;
struct gadget;
typedef struct gadget gadget_t;
widget_t *newWidget(void)
{
widget_t *p = malloc(sizeof *p);
if (p)
/* initialize members of *p as necessary */
return p;
}
gadget_t *newGadget(void)
{
gadget_t *p = malloc(sizeof *p);
if (p)
/* initialize members of *p as necessary */
return p;
}
void deleteWidget(widget_t **p)
{
/* delete any subelements of *p */
free(*p);
*p = NULL;
}
void deleteGadget(gadget_t **p)
{
/* delete any subelements of *p */
free(*p);
*p = NULL;
}
...
widget_t *p = newWidget();
gadget_t *g = newGadget();
if (p)
/* do stuff with p */
if (g)
/* do stuff with g */
...
deleteWidget(&p);
deleteGadget(&g);
【问题讨论】:
-
p = malloc(sizeof *p)比p = malloc(sizeof (some_type))更容易查看。第二种形式要求检查“类型是否正确”。第一个在构造上是正确的。