You are on page 1of 7

Dynamic Memory Allocation

Introduction
 Array is a collection of items stored in a continuous memory location.
 Can we change the size of the array once it is declared?
 For Eg: int arr[10] = {10,20,30,40,50}
 In the above example the size of the array is declared as 10 but the
array contains only 5 elements. The remaining 5 indices are wasting
the memory resource.
 In another case, if the size of the array is 10 but we need to store 15
elements, now can we change the size of the array?
 The above two cases are made possible with Dynamic Memory
Allocation
Dynamic Memory Allocation
 Dynamic Memory Allocation can be defined as a procedure in
which the size of a data structure (like Array) is changed during the
runtime.
 There are 4 library functions provided by C defined
under <stdlib.h> header file to facilitate dynamic memory
allocation in C programming.
1. malloc()  Used to allocate memory to structure (User defined datatypes)
2. calloc()  To arrays
3. realloc()  Increase/decrease size of array
4. free()  delete the memory
malloc()
 “malloc” or “memory allocation” method in C is used to dynamically
allocate a single large block of memory with the specified size.
Syntax:
ptr = (cast-type*) malloc(byte-size)
For Example:
int *ptr;
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of
memory. And, the pointer ptr holds the address of the first byte in the
allocated memory.
free()
 “free” method in C is used to dynamically de-allocate the memory.
 The memory allocated using function malloc() is not de-allocated
on their own.
 Hence the free() method is used, whenever the dynamic memory
allocation takes place.
 It helps to reduce wastage of memory by freeing it.
Syntax: free(ptr);
Example

int main(){
struct emp *ptr;

#include<stdio.h> ptr=(struct emp*)malloc(sizeof(struct emp));


#include<stdlib.h>
if(ptr==NULL){
struct emp{ printf("Memory not allocated");
int eno; }
char ename[10]; else{
float sal; printf("Enter eno ename and salary");
scanf("%d%s%f",&ptr->eno,ptr->ename,&ptr->sal);
}; }

printf("The details are as follows: \nThe name %s\nThe eno is %d\nThe


salary is: %f",ptr->ename,ptr->eno,ptr->sal);
}

You might also like