#include <stdlib.h> void *malloc(size_t size);
malloc
allocates a block of dynamic memory of the size requested by
size
.
malloc
returns the address of the first character of the new block of
memory. The allocated block is suitably aligned for storage of any type of
data.
NULL
is returned.
Storage is always obtained from the operating system in page multiples and only when necessary. Small blocks are kept separate from large blocks to reduce fragmentation.
Under an XA or ESA operating system, memory allocated by malloc
can
reside above the 16-megabyte line for programs that run in 31-bit
addressing mode.
Allocation of a large number of small blocks or of blocks that are slightly
larger than half a page may result in significant waste of memory. Use of the
pool
, palloc
, and pfree
routines is recommended in such
cases.
#include <stdlib.h> #include <stdio.h> #include <string.h> char *source, *copy; main() { source = "A simple line for the malloc example "; /* Allocate space for a copy for source. */ copy = malloc(strlen(source) + 1); /* Copy if there is space. */ if (copy){ strcpy(copy,source); puts(copy); } else puts("malloc failed to allocate memory for copy".); }
pool
, realloc
, sbrk
Copyright (c) 1998 SAS Institute Inc. Cary, NC, USA. All rights reserved.