DYNAMIC MEMORY ALLOCATION


Note : - In C language Dynamic Memory allocation is perform  in heap area of memory.

* Malloc Allocation :-

-  Here 'm' means memory & 'alloc' means allocation.
-  It is used to allocate space for variable, array, structure, etc. in memory dynamically i.e at run time. It returns the address of allocated space after allocation. The return type of malloc() function is generic pointer / void pointer and garbage value is stored as default value of allocated space.
    The prototype of malloc()  is specified in stdlib.h.
Syntax : pointer variable = (cast-type *) malloc (size of byte)

Example :- 
        1.) int x; // static memory allocation.
         2.)  int *p;
               p=(int*)malloc(sizeof(int));
               *p=15;
               float *p;

1.)   Write a program to print the sum of two number memory must be allocated dynamically.

/* Addition with Dynamic Memory Allocation using malloc() function. */
    #include<stdio.h>
    #include<stdlib.h>
    #include<conio.h>
    void main()
    {
int *first, *second, *third;
first=(int *)ma lloc(sizeof(int));
second=(int *)malloc(sizeof(int));
third=(int *)malloc(sizeof(int));
printf ("Enter First Number = ");
scanf ("%d",first);
printf ("Enter Second Number = ");
scanf ("%d",second);
*third = *second + *first;
printf ("Sum of First & Second %d",*third);
getch();
    }



2.)   Write a program to print the absolute value of a number.
/* Finding absolute value of a number with Dynamic Memory Allocation using malloc() function. */
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
int *num;
num=(int *)malloc(sizeof(int));
printf ("Enter a Number = ");
scanf ("%d",num);
if (*num < 0)
{
printf ("%d",(*num)*-1);
}
else
{
printf ("%d",*num);
}
getch();



3.)   Write a program to check a number is spy number or not.

/* Checking given number is spy or not with Dynamic Memory Allocation using malloc() function. */
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
int *num, *rem, *sum, *product, *a;
num=(int *)malloc(sizeof(int));
rem=(int *)malloc(sizeof(int));
sum=(int *)malloc(sizeof(int));
printf ("Enter a Number = ");
scanf ("%d",num);
*a = *num;
*sum = 0;
*product = 1;
while ((*num)>0)
{
*rem=(*num)%10;
*sum=(*sum)+(*rem);
*product=(*product)*(*rem);
*num=(*num)/10;
}
if ((*sum)==(*product))
{
printf ("%d is spy number",*a);
}
else
{
printf (" is not spy number",*a);
}
getch();
}