Nalin Kanwar
Nalin Kanwar

Reputation: 120

sizeof operator and structs

struct s  
{  
    int i;  
    char * c;  
} *obj;
obj = malloc(sizeof(struct s));

Say for example we have a struct as defined above (or any struct in general, i just wrote the above one for the sake of example).

Then, what is better when using the sizeof operator

sizeof(struct s) or sizeof(*obj) ?

I prefer the first one since it makes more sense to me (clearly tells us that we're allocating memory for an object of struct s)

Also, using the second one can introduce logical errors (like the usual 'forgetting to dereference the pointer')

Can the first one cause any problems? I haven't had problems with it yet but just wanted to know whether what i'm doing is proper or not.

If so, can you please provide an example of where it can fail?

Upvotes: 1

Views: 1004

Answers (3)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272802

Either may be used.

sizeof(*obj) should always be used, though, because if the type of obj ever changes, this will still work. With sizeof(struct s), you will have a latent bug.

Upvotes: 3

Ed Heal
Ed Heal

Reputation: 60037

I prefer the sizeof(struct s) despite if the structures name changes the code is out of date. My philosophy is thaat if the structure changes it is best to revist the code that uses it just to be on the safe side.

Upvotes: -2

cnicutar
cnicutar

Reputation: 182774

Then, what is better when using the sizeof operator

sizeof(struct s) or sizeof(*obj) ?

It's a matter of preference.

I prefer sizeof(*obj). If I later change the type of obj (say, struct s2), sizeof(struct s) will be out of date.

Upvotes: 7

Related Questions