Dynamic Memory Allocation in C using Malloc

Dynamic memory allocation using malloc function in C :

On this page we will discuss about dynamic memory allocation using Malloc function in C programming language. A memory block of specified size is allocate at run time by malloc.A pointer of void type is returned by malloc function which can be convert into pointer of any type.
Dynamic Memory Allocation using malloc

Dynamic memory allocation using malloc function

Array is used to store the items of same data types at a contiguous memory location. But if we don’t know the amount of size we required there is chance of wastage of storage if the elements inserted in array are lesser than the size allocated.

So to avoid this problem  the concept of dynamic memory allocation comes in play. malloc() is a predefined function inside stdlib. h header file.Malloc() allocate a large block of memory of specifies size at run time.It returns a pointer of void type which can be converted to any type of pointer.

Syntax:   

ptr = (cast-type*) malloc(byte-size)

Note: ptr will hold the address of first byte of the memory that is allocated.

For Example:
Dynamic memory allocation in C using malloc

Implementation of dynamic memory allocation using malloc :

Run
#include <stdio.h>
#include <stdlib.h>
int main ()
{
  int a, j, *ptr, s = 0;

  printf ("Enter number of elements: ");
  scanf ("%d", &a);

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


  if (ptr == NULL)
    {
      printf ("Error! memory cannot be allocated.");
      return 0;
    }

  printf ("Enter the elements: ");
  for (j = 0; j < a; ++j)
    {
      scanf ("%d", ptr + j);
      s += *(ptr + j);
    }

  printf ("Sum of elements = %d ", s);


  free (ptr);			// deallocation of memory

  return 0;
}

Output:

Enter number of elements: 4
Enter elements: 10
12
8
6
Sum = 36 

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription