COHERENT manpages
This page displays the COHERENT manpage for malloc() [Allocate dynamic memory].
List of available manpages
Index
malloc() -- General Function (libc)
Allocate dynamic memory
#include <stdlib.h>
char *malloc(size) unsigned size;
malloc() helps to manage a program's free-space arenas. It uses a
circular, first-fit algorithm to select an unused block of at least size
bytes, marks the portion it uses, and returns a pointer to it. The
function free() returns allocated memory to the free memory pool.
Each arena allocated by malloc() is rounded up to the nearest even number
and preceded by an unsigned int that contains the true length. Thus, if
you ask for three bytes you get four, and the unsigned that precedes the
newly allocated arena is set to four.
When an arena is freed, its low order bit is turned on; consolidation
occurs when malloc() passes over an arena as it searches for space. The
end of each arena contains a block with a length of zero, followed by a
pointer to the next arena. Arenas point in a circle.
The most common problem with malloc() occurs when a program modifies more
space than it allocates with malloc(). This can cause later malloc()s to
crash with a message that indicates that the arena has been corrupted. You
can use the function memok() to isolate these problems.
Example
This example reads from the standard input up to NITEMS items, each of
which is up to MAXLEN long, sorts them, and writes the sorted list onto the
standard output. It demonstrates the functions qsort(), malloc(), free(),
exit(), and strcmp().
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NITEMS 512
#define MAXLEN 256
char *data[NITEMS];
char string[MAXLEN];
main()
{
register char **cpp;
register int count;
extern int compare();
for (cpp = &data[0]; cpp < &data[NITEMS]; cpp++) {
if (gets(string) == NULL)
break;
if ((*cpp = malloc(strlen(string) + 1)) == NULL)
exit(1);
strcpy(*cpp, string);
}
count = cpp - &data[0];
qsort(data, count, sizeof(char *), compare);
for (cpp = &data[0]; cpp < &data[count]; cpp++) {
printf("%s\n", *cpp);
free(*cpp);
}
exit(0);
}
compare(p1, p2)
register char **p1, **p2;
{
extern int strcmp();
return(strcmp(*p1, *p2));
}
See Also
alloca(),
arena,
calloc(),
free(),
libc,
memok(),
realloc(),
setbuf(),
stdlib.h
ANSI Standard, §7.10.3.3
POSIX Standard, §8.1
Diagnostics
malloc() returns NULL if insufficient memory is available.
Notes
The function alloca() allocates space on the stack. The space so allocated
does not need to be freed when the function that allocated the space exits.