- The malloc() function allocates an uninitialized memory block. It allocates a specified number of bytes of memory, as shown in the following prototype, returning a pointer to the newly allocated memory or NULL on failure:
void *malloc(size_t size);
- The calloc() function allocates and initializes a memory block. The difference is that calloc() initializes the allocated memory, setting each bit to 0, returning a pointer to the memory or NULL on failure. It uses the following prototype:
void *calloc(size_t nmemb, size_t size);
- The realloc() function resizes a previously allocated memory block. Use realloc() to resize memory previously obtained with a malloc() or calloc() call. This function uses the following prototype:
void *realloc(void *ptr, size_t size);
- The ptr argument must be a pointer returned by malloc() or calloc().
- The size argument may be larger or smaller than the size of the original pointer.
- The free() function frees a block of memory. This function uses the following prototype:
void free(void *ptr);
- The ptr argument must be a pointer returned from a previous call to malloc() or calloc().
- It is an error to attempt to access memory that has been freed.
Memory allocation functions obtain memory from a storage pool known as the heap.
- The alloca() function allocates an uninitialized block of memory. This function uses the following prototype:
void *alloca(size_t size);
alloca() obtains memory from the process's stack rather than the heap and, when the function that invoked alloca() returns, the allocated memory is automatically freed.