6.19.23 malloc Function

Dynamically allocate a block of memory from the heap.

Include

<stdlib.h>

Prototype

void * malloc(size_t size);

Argument

size
number of bytes to dynamically allocate

Return Value

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

Remarks

Although the memory block allocated and whose address is returned will be large enough to hold an object with the specified size, the memory required to allocate that block might be larger than the requested size due to alignment of the allocated memory, and/or additional objects that are used to manage the heap.

Unlike calloc, the malloc function does not initialize the memory it allocates.

See your MPLAB XC compiler User's Guide for more information on dynamic memory allocation.

Example

#include <stdio.h>
#include <stdlib.h>

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