Dynamic Memory



Dynamic memory is the process of obtaining memory by the programmer in the program by requesting the operating system to allocate memory and if memory is available then the operating system  allocates memory to the program
Dynamic memory is created when we need it and destroyed when we are finished with it , we use the malloc function in order to obtain memory from the operating system , mellocs are used extensively used with pointers in order to function properly

The syntax looks like 

#include<stdlib.h>
int * ptr
ptr = malloc(100);

we have to use the c standard library stdlib for the malloc function to function  ,
we create a  pointer pointing towards an integer
now we use the pointer to assign memory of 100 bytes , but instead of typing a number we can write the following

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

the above syntax means that we need memory for storing 25 integers so we have 25 multiply by size of a int that would in most case 25 * 4 = 100 byte

some malloc programs are

#include<stdio.h>
#include<stdlib.h>
main()
{
int i;
int sum = 0;
float ans = 0;
int total;
int *avg;


printf("Total Numbers Of Number \n ");
fflush(stdin);
scanf("%d",&total);

avg = malloc(total * sizeof(int));

if(total == NULL)
{
 printf("malloc error \n");
 exit(1);       
}

for(i=0;i<total;i++)
{
 printf("Enter number %d ........ \n",i+1);
 fflush(stdin);
 scanf("%d", &avg[i]);                  
 sum = sum + avg[i];
}
free(avg);
ans =(float) sum/total;

printf(" Average is %f ",ans);
getch();    
}

In this program we ask the user for a number that would be the total number of number of which we would find average , we store this value in “total” , now we ask the OS to allocate memory for that amount integer and we use a pointer to refer to it “avg” , sometime the system may not be able to provide memory so to tackle this situation we have written this piece of code

if(total == NULL)
{
 printf("malloc error \n");
 exit(1);       
}

Which means if no memory is available then exit the program , now we use a for loop which runs the “total” time and with each run we accepts a number from the user which is summed up in the variable sum , then we free the memory used using the free function and finally we display the average


No comments:

Post a Comment