Kristofer
Kristofer

Reputation: 1487

Using unsigned long long int for dynamic allocation

If I have the following variable unsigned long long int *size, is it a good practice to leave size = calloc(2, sizeof(int)) or it should be size = calloc(2, sizeof(unsigned long long int)) ?

Thank you

Upvotes: 1

Views: 1312

Answers (3)

ad absurdum
ad absurdum

Reputation: 21358

There is no reason to assume that intand unsigned long long int are the same size (they may be). If size is declared as unsigned long long int, then of the two options presented, the correct choice is:

size = calloc(2, sizeof(unsigned long long int));

A better practice is to avoid using explicit types with sizeof:

size = calloc(2, sizeof *size);

This is less error-prone in the initial coding, and more maintainable. If types change during the lifetime of the code, only the declaration needs to be changed here.

Upvotes: 2

Ran Eldan
Ran Eldan

Reputation: 1350

The size of int can be either 2 or 4 bytes, depending on the machine you run.
However, the size of unsigned long long is at least 8 bytes.

So no, it is NOT a good practice to use a worng size.

Upvotes: 0

Yuval Ben-Arie
Yuval Ben-Arie

Reputation: 1290

Second option. You don't want to make assumptions about datatype sizes in c.
It is very platform/compiler dependent.

Upvotes: 2

Related Questions