Reputation: 1498
I have always used the malloc
function as, for exemple,
int size = 10000;
int *a;
a = malloc(size * sizeof(int));
I recently run into a piece of code that discards the sizeof(int)
part, i.e.
int size = 10000;
int *a;
a = malloc(size);
This second code seems to be working fine.
My question is then, which form is correct? If the second form is, am I allocating needless space with the first form.
Upvotes: 2
Views: 3205
Reputation:
From the man page:
The malloc() function allocates size bytes and returns a pointer to the allocated memory.
The first form is correct.
Even if the sizeof(int) on the machine you are targeting is one (which is sometimes true on 8-bit microcontrollers) you still want your code to be readable.
The reason the "second code seems to be working fine" is that you are lucky.
The version of malloc you are using might be returning a pointer to an area of memory that is larger than what you requested. No matter what is happening behind the scenes, the behavior may change if you switch to a different compiler, so you do not want to rely on it.
Upvotes: 2
Reputation: 476990
malloc
allocates a given number of bytes worth of memory, suitably aligned for any type. If you want to store N
elements of type T
, you need N * sizeof(T)
bytes of aligned storage. Typically, T * p = malloc(N * sizeof(T))
provides that and lets you index the elements as p[i]
for i
in [0, N).
Upvotes: 3
Reputation: 363547
The argument to malloc
is the number of bytes to be allocated. If you need space for an array of n
elements of type T
, call malloc(n * sizeof(T))
. malloc
does not know about types, it only cares about bytes.
The only exception is that when you allocate space for (byte/char
) strings, the sizeof
can be omitted because sizeof(char) == 1
per definition in C. Doing something like
int *a = malloc(10000);
a[9000] = 0;
may seem to work now, but actually exploits undefined behavior.
Upvotes: 6