gpt4 book ai didi

c - 不使用 sizeof(type),使用 sizeof *p,是否安全正确?

转载 作者:行者123 更新时间:2023-12-04 22:02:44 24 4
gpt4 key购买 nike

这是否可以安全使用,此代码使用 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);

最佳答案

sizeof 运算符具有以下定义

sizeof unary-expression
sizeof ( type-name )

因此在这个声明中
widget_t *p = malloc(sizeof *p);

使用了运算符的第一种形式,其中表达式 *p 是一元表达式并且具有 widget_t 类型。

因此这些声明
widget_t *p = malloc(sizeof *p);
widget_t *p = malloc(sizeof( widget_t ) );

是完全等效的。

第一个声明更可取,因为 sizeof 运算符中的表达式不依赖于实际类型。即指针的类型可以更改,但声明将有效而无需任何其他更改。

在 C 中,不需要将从 malloc 返回的指针强制转换为分配的左值的类型,因为 void * 类型的指针可以分配给指向任何类型对象的指针。它有时用于(而且有时有用)使程序自记录。

关于c - 不使用 sizeof(type),使用 sizeof *p,是否安全正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58501748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com