Reputation: 24111
Whenever I see malloc
in someone else's code, it typically uses sizeof(short)
or sizeof(double)
etc. to help define the size of memory to be allocated. Why do they not just replace those expressions with 2
or 8
, in those two examples?
Upvotes: 0
Views: 151
Reputation: 123458
The most portable and maintainable way to write a malloc
call in C is:
T *p = malloc( N * sizeof *p );
or
T *p;
...
p = malloc( N * sizeof *p );
where T
is any arbitrary type and N
is the number of objects of that type you want to allocate. Type sizes are not uniform across platforms, and the respective language standards only mandate minimum ranges of values that non-char
types must be able to represent. For example, an int
must represent at least the range [-32767...32767]
, meaning it must be at least 16 bits wide, although it may be (and often is) wider. For another example, struct
types may have different amounts of padding between members depending on the platform's alignment requirements, so a struct foo
type may take up 24 bytes on one platform and 32 on another.
The expression *p
has type T
, so sizeof *p
gives the same result as sizeof (T)
, which is the number of bytes required to store an object of type T
. This will always give you the right number of bytes to store your object (or sequence of objects), regardless of platform, and if you ever change T
(from int
to long
, for example), you don't have to go back and change the arguments to the malloc
call.
Note that you shouldn't use malloc
or calloc
in C++ code; you should use a standard container like a vector
or map
that handles all the memory management for you. If for some reason a standard container doesn't meet your needs, use the new
operator to allocate a single object of type T
and new []
to allocate an array of objects.
Upvotes: 1
Reputation: 234635
Neither the size of a double or a short is fixed by the c++ standard. Note that for a double, it doesn't even have to be an IEEE754 floating point type. In this respect c++ differs from Java. So it would be a poor idea to hardcode the size.
And use new
/ new[]
and delete
/ delete[]
in C++.
Upvotes: 0
Reputation: 28837
It makes the code easier to port.
In general there are compiler options which allow you to say how data is to be alligned in a struct. The size of a double may vary between platforms. By consistantly using the data type, you reduce the occurance of some types of size mismatch errors.
I think it is a better practice to use the variable name instead of the data type for the size of piece.
float Pi = 3.14f;
float *pieArray = (float *) malloc(sizeof (Pi) * 1000);
Personally I would prefer this method.
typedef float Pi;
Pi *piArray = new Pi[1000];
// use it
delete[] piArray;
new/delete should be preferred over malloc/free in most cases.
Upvotes: 4