malloc

From Appmethod Topics
Jump to: navigation, search

Go Up to alloc.h Index


Header File

alloc.h, stdlib.h

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 is 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.

Portability

POSIX ANSI C ANSI C++ Win32 Win64 OS X
malloc + + + +

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;
}