Upload
rohit-shrivastava
View
246
Download
0
Embed Size (px)
Citation preview
Dynamic Memory Allocation
Basic Idea• Many a time we face situations where data is dynamic in
nature.• – Amount of data cannot be predicted beforehand.• – Number of data items keeps changing during program execution.• Such situations can be handled more easily and effectively
using dynamic memory management techniques.• C language requires the number of elements in an array to be
specified at compile time.• – Often leads to wastage of memory space or program failure.• Dynamic Memory Allocation• – Memory space required can be specified at the time of execution.• – C supports allocating and freeing memory dynamically using
library routines.
Memory Allocation Process in C• Memory allocated to any program is either from Stack or Heap.• Stack memory is allocated to local variable, function call parameters etc.• Heap memory is allocated to global variables or the variables which request
for memory space and asking for memory space is called dynamic allocation of memory.
• Four basic functions which belong to stdlib.h or malloc.h or alloc.h for dynamic memory allocation –
1. malloc()2. calloc()3. realloc()4. free()
Examplevoid main(){
int i,N;float *height;float sum=0,avg;printf("Input no. of students\n");scanf("%d", &N);height = (float *) malloc(N * sizeof(float));printf("Input heights for %d students \n",N);for (i=0; i<N; i++)
scanf ("%f", &height[i]);for(i=0;i<N;i++)
sum += height[i];avg = sum / (float) N;printf("Average height = %f \n“,avg);free (height);
}
Calloc()• Calloc function allocates the block of bytes from
heap.• Syntax: void * calloc (num, size) • This function takes two arguments that specify
the number of elements to be reserved, and the size of each element in bytes
• It allocates memory block equivalent to num* size .
Example2: calloc and malloc
Realloc Examplevoid main() {
int* array,*array1;int n, i;printf("Enter the number of elements: ");scanf("%d", &n);array = (int*) calloc(n,sizeof(int));for (i=0; i<n; i++) {
printf("Enter number %d: ", i);scanf("%d", &array[i]);
}array1 = (int*) realloc(array,(n+1)*sizeof(int));if(array1)
printf("Memory Allocated");printf("\nThe Dynamic Array is: \n");for (i=0; i<(n+1); i++)
printf("The value of %d is %d\n", i, array1[i]);}
O/P?#include <malloc.h>#include <stdio.h>void main() {
int* ptr;ptr=(int *)malloc(sizeof(int));*ptr=5;printf("%d ",*ptr);free(ptr);*ptr=7;printf("%d ",*ptr);
}