Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper argument for malloc

Tags:

c

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.

like image 710
rpsml Avatar asked Dec 13 '25 00:12

rpsml


2 Answers

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.

like image 160
Fred Foo Avatar answered Dec 15 '25 14:12

Fred Foo


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).

like image 35
Kerrek SB Avatar answered Dec 15 '25 13:12

Kerrek SB