malloc Function

Allocates memory.

The default implementation of malloc will require an additional 4 bytes of heap memory per allocation.

The legacy library's malloc will use an additional 2 bytes of heap memory per allocation.

Include

<stdlib.h>

Prototype

void *malloc(size_t size);

Argument

size number of characters to allocate

Return Value

Returns a pointer to the allocated space if successful; otherwise, returns a null pointer.

Remarks

malloc does not initialize memory it returns. This function requires a heap.

Example

#include <stdio.h>  /* for printf, sizeof, */
                    /* NULL                */
#include <stdlib.h> /* for malloc, free    */

int main(void)
{
  long *i;

  if ((i = (long *)malloc(50 * sizeof(long))) ==
      NULL)
    printf("Cannot allocate memory\n");
  else
  {
    printf("Memory allocated\n");
    free(i);
    printf("Memory freed\n");
  }
}

Example Output

Memory allocated
Memory freed