Dynamic Memory Allocation using malloc()

Dynamic Memory Allocation using malloc()

In this tutorial, you are going to learn about Dynamic Memory Allocation using malloc(), use of void pointer in dynamic memory allocation using malloc() and programming example malloc function.

What is Malloc()

It is a Built-in function declared in the header file <stdlib.h>. Malloc is a short name for “memory allocation” and is used to dynamically allocate a single large block of contiguous memory according to the size specified.

Syntax: (void*)malloc(size_t size)

Malloc function simply allocates a memory block according to the size specified in the heap and on success it returns a pointer pointing to the first byte of the allocated memory else returns NULL.

size_t is defined in <stdlib.h> as unsigned int.

In HEAP a contiguous block of memory is allocated using malloc() and it will return a pointer, which is basically a void pointer assuming that pointer is ptr which is pointing towards a particular memory.

Why does Malloc() returns a Void Pointer

Malloc does not have any idea of what it is pointing to. It merely allocates memory requested by the user without knowing the type of data to be stored inside the memory.

The void pointer can be typecasted to an appropriate type.

int *ptr = (int*)malloc(4)

Malloc allocates 4 bytes of memory in the heap and the address of the first byte is stored in the pointer (i.e *ptr).

ptr = (int*)malloc(100*sizeof(int));

Since the size of int is 4 byte, this statement will allocate 400 bytes of memory, And, the pointer ptr holds the address of first byte in the allocated memory.

Programming Example - Malloc Function

#include <stdio.h>
#include <stdlib.h>
int main()
int i,n;
printf(“Enter the number of integers: “);
int *ptr = (int*)malloc(n*sizeof(int));
if (*ptr==NULL)
   printf(“Memory is not available”);
   for (i=0; i<n;i++);
   printf(“Enter an Integer:”);
   scanf(“%d”,ptr + i);
   for (i=0;i<n;i++)
   return 0;

This post on Dynamic Memory Allocation using malloc() is contributed by Aditya Raj. If you like TheCode11, then do follow us on Facebook, Twitter and Instagram.

Previous Post Next Post

Contact Form