Syntax
#include <stdlib.h> /* also in <malloc.h> */ void *malloc(size_t size);Description
malloc reserves a block of storage of size bytes. Unlike calloc, malloc does not initialize all elements to 0.
Heap-specific and debug versions of this function (_umalloc and _debug_malloc) are also available. malloc always operates on the default heap. For more information about memory management, see "Managing Memory" in the VisualAge C++ Programming Guide.
malloc returns a pointer to the reserved space. The storage space to which the return value points is suitably aligned for storage of any type of object. The return value is NULL if not enough storage is available, or if size was specified as zero.
This example prompts for the number of array entries you want and then reserves enough space in storage for the entries. If malloc was successful, the example assigns values to the entries and prints out each entry; otherwise, it prints out an error.
#include <stdio.h> #include <stdlib.h> int main(void) { long *array; /* start of the array */ long *index; /* index variable */ int i; /* index variable */ int num; /* number of entries of the array */ printf("Enter the size of the array\n"); scanf("%i", &num); /* allocate num entries */ if ((index = array = malloc(num *sizeof(long))) != NULL) { for (i = 0; i < num; ++i) /* put values in array */ *index++ = i; /* using pointer notation */ for (i = 0; i < num; ++i) /* print the array out */ printf("array[ %i ] = %i\n", i, array[i]); } else { /* malloc error */ perror("Out of storage"); abort(); } return 0; /**************************************************************************** The output should be similar to: Enter the size of the array 5 array[ 0 ] = 0 array[ 1 ] = 1 array[ 2 ] = 2 array[ 3 ] = 3 array[ 4 ] = 4 ****************************************************************************/ }Related Information