Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof(struct ExampleStruct) or sizeof( *VarExampleStruct) - Which is a better coding practice?

Tags:

c

structure

While mentioning the size of a structure to a malloc call, is it better to mention the name of the structure or the dereferenced structure pointer variable?

Example:

struct ExampleStruct
{
  int x;
  char arr[40];
};

int main()
{

  struct ExampleStruct *Y = NULL;

  Y = malloc(sizeof(struct ExampleStruct)); //Is this better?

  Y = malloc(sizeof(*Y)); //Is this better?  

}

I personally prefer sizeof(struct ExampleStruct) as I have seen many developers making the mistake missing the '*' in the second method, i.e. they erroneously type it as malloc(sizeof(Y)) and in this case, the memory allocated will be only 4 bytes. But, I have seen it being used commonly also.

like image 474
Jay Avatar asked Dec 21 '22 21:12

Jay


2 Answers

I definitely prefer the 2nd. If the declared type of Y every changes, the line will still work correctly.

like image 179
Robᵩ Avatar answered Dec 23 '22 10:12

Robᵩ


I looked in K&R 2nd Edition, and found 3 relevant examples of using malloc():

  • Page 142: return (struct tnode *) malloc(sizeof(struct tnode));

  • Page 145: np = (struct nlist *) malloc(sizeof(*np));

  • Page 146: return (Treeptr) malloc(sizeof(Treenode));

There was no particular discussion of the different forms. There's a note in the preface 'We used Bjarne Stroustrup's C++ translator extensively for local testing of our programs'. This was written just before the 1989 C Standard was finalized (my copy has 'Based on the Draft Proposed ANSI C' on the cover, so there were no standard compilers at the time), and this may explain the explicit casts on every malloc() call — those are necessary in C++.

So, the 'founders' used both forms.

Modern style is to use the sizeof(*variable) notation (and, in C, to omit the cast) so that even if the type of the variable changes, you won't have to change this code. Add the cast, and that benefit goes away.

Most of my older code tends to use the sizeof(type) notation, in part in emulation of the style in K&R C. Most of my newer code now uses the sizeof(*variable) notation. When I expect to compile the code with C++ as well as C, I put the cast in too.

like image 40
Jonathan Leffler Avatar answered Dec 23 '22 10:12

Jonathan Leffler