Dynamic memory management is built into Java through
its new
keyword and its
garbage collector. In C, it is available through two
functions in <stdlib.h>
which are
declared as:
void *malloc(size_t s); /* Reserve memory fors
char
s. */ void free(void *); /* Release memory reserved withmalloc
. */
(size_t
is an alias
for an unsigned integral type.)
malloc(s)
returns a pointer to the start of a block of memory big
enough for s char
s.
It returns a generic pointer which can be assigned to a
pointer variable of any type. The memory is not
initialised. All such allocated memory must be released
when it is no longer required, by passing a pointer to
its start to free()
. Only
pointer values returned by malloc()
can be passed to free()
.
You can find out the amount of memory needed to store
an object of a particular type using sizeof(type)
.
For an array, multiply this by the number of elements
required in the array.
long *lp; long *lap; lp = malloc(sizeof(long)); lap = malloc(sizeof(long) * 10); /* Now we can access*lp
as a long integer, andlap[0]
..lap[9]
form an array. */ free(lap); free(lp); /* Now we can't. */
malloc()
returns a null pointer (0
) if
it cannot allocate the requested amount of memory.