malloc
Allocates main memory.
Defined in header <stdlib.h>
Syntax
#include <stdlib.h> or #include <alloc.h>
void *malloc(size_t size);
Portability
| DOS | UNIX | Windows | ANSI C | C++ only |
|---|---|---|---|---|
| ■ | ■ | ■ | ■ |
Remarks
malloc allocates a block of size bytes from the memory heap. It allows a program to allocate memory explicitly as it's needed, and in the exact amounts needed.
The heap is used for dynamic allocation of variable-sized blocks of m.emory. Many data structures, such as trees and lists, naturally employ heap memory allocation.
All the space between the end of the data segment and the top of the program stack is available for use in the small data models, except for a small margin immediately before the top of the stack. This margin is intended to allow the application some room to make the stack larger, in addition to a small amount needed by DOS.
In the large data models, all the space beyond the program stack to the end of available memory is available for the heap.
Return value
On success, malloc returns a pointer to the newly allocated block of memory. If not enough space exists for the new block, it returns null. The contents of the block are left unchanged. If the argument size == 0, malloc returns null.
See also
Example
#include <stdio.h>
#include <string.h>
#include <alloc.h>
#include <process.h>
int main (void)
{
char *str;
/* allocate memory for string V
if ((str = (char *) malloc(10)) == NULL) {
printf ("Not enough memory to allocate buffer\n"
exit(l); /* terminate program if out of memory */
}
/* copy "Hello" into string */
strcpy(str, "Hello");
/* display string */
printf ("String is %s\n", str);
/* free memory */
free (str);
return 0;
Differences from modern implementations
Nothing recorded yet.
Modern references
These are search links, not yet checked by hand.
Stable link: /3.1/stdlib.h/malloc/
· short form /3.1/malloc/