C Standard Library

C <stdlib.h> - malloc() Function



The C <stdlib.h> malloc() function is used to allocate a block of size bytes of memory. If allocation succeeds, it returns a pointer to the beginning of newly allocated memory.

The content of the newly allocated memory is not initialized, remaining with indeterminate values.

If size is zero, the behavior of the function is implementation-defined (it may or may not be a null pointer), but the returned pointer shall not be dereferenced, and should be passed to free() to avoid memory leaks.

Syntax

void* malloc (size_t size);

Parameters

size Specify number of bytes to allocate.
size_t is an unsigned integral type.

Return Value

On success, returns a pointer to the beginning of newly allocated memory. The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable. On failure, returns a null pointer.

Example:

The example below shows the usage of <stdlib.h> malloc() function.

#include <stdio.h>
#include <stdlib.h>
 
int main (){
  //allocating memory for array of 5 int
  int *p1 = (int*) malloc(5*sizeof(int)); 
  
  //another way of doing the same
  int *p2 = (int*) malloc(sizeof(int[5]));

  //another way of doing the same
  int *p3 = (int*) malloc(5*sizeof *p3);

  //populating the array
  for(int i=0; i<5; i++)
	p1[i] = (i+1)*10;

  //displaying the array
  for(int i=0; i<5; i++)
	printf("p1[%d] = %d\n", i, p1[i]);

  //deallocating previously allocated memory
  free(p1);
  free(p2);
  free(p3);
  return 0;
}

The output of the above code will be:

p1[0] = 10
p1[1] = 20
p1[2] = 30
p1[3] = 40
p1[4] = 50

❮ C <stdlib.h> Library