Is this safe to use,This code compiled with gcc 4.9.2 without any error or warning
widget *p;
...
p = malloc(sizeof *p);
I found this on SEI CERT C Coding Standard website.
Click here -- no type mismatch issues, no need for casting. You allocate the right amount of memory every time.
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);