Jump to content

C dynamic memory allocation

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Dysprosia (talk | contribs) at 09:01, 1 December 2003 (a start). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

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.