Header File
alloc.h, stdlib.h
Category
Memory Routines
Prototype
void *malloc(size_t size);
Description
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.
Allocates main memory.The heap is used for dynamic allocation of variable-sized blocks of memory. Many data structures, for example, trees and lists, naturally employ heap memory allocation.
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.
Example
#include <stdio.h> #include <string.h> #include <alloc.h> #include <process.h> int main(void) { char *str; /* allocate memory for string */ if ((str = (char *) malloc(10)) == NULL) { printf("Not enough memory to allocate buffer\n"); exit(1); /* 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; }
Portability
POSIX |
Win32 |
ANSI C |
ANSI C++ |
+ |
+ |
+ |
+ |
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
|
What do you think about this topic? Send feedback!
|