Main Page | See live article | Alphabetical index

Malloc

malloc is a tool for allocating memory dynamically in the C programming language. Without malloc, memory allocation must be done "at once".

For example, if we wish to create an array of ten integers, without malloc we may say

int x[10];
/* statements */

With malloc we can merely create a pointer to the first element of the array and make this point to malloc'd memory.
int *x = malloc(sizeof(int)*10);

Now this does not seem to have gained us much, but the use of malloc allows us to perform the following
int *x;
/* statements */
x = malloc(sizeof(int)*10); /* Now we can use the array, where we
                               may not have needed to before */

or
int *x = malloc(sizeof(int)*2);
x[0]=2;
x[1]=3;
/* etc */
free(x); /* release the memory */
x = malloc(sizeof(int)*5); /* Now we have space for five integers */

With it's companion function realloc we can create dynamically sized arrays in C.

See also