SlideShare a Scribd company logo
1 of 36
Dynamic Memory Allocation
&
Linked Lists
Prepared by: Moniruzzaman_CSE_KU_190231
Dynamic memory location:
• The process of allocating memory at run time is known as dynamic memory
allocation.
• C does not inherently have this facility. There are four library routines known as
memory management functions that can be used for allocating and freeing
memory during execution.
• malloc(), calloc(), free(), realloc()
• All are defined in alloc.h
Prepared by: Moniruzzaman_CSE_KU_190231
malloc: Allocating a block of memory
• General form
• ptr = (cast-type *) malloc(byte-size);
• ptr is a pointer of type cast-type
• The malloc() returns a pointer (of cast-type) to an area of memory with size byte-size. If
there is not enough space a NULL pointer is returned.
• Example
• x=(int *) malloc(100*sizeof(int));
• cptr=(char *) malloc(10);
• st= (struct *) malloc(sizeof(struct store));
• Storage space allocated dynamically has no name and therefore its contents can be
accessed only through a pointer.
Prepared by: Moniruzzaman_CSE_KU_190231
calloc: Allocating multiple block of memory
• While malloc() allocates a single block of storage space, calloc() allocates
multiple blocks of storage, each of the same size, and then set all bytes to zero.
If there is not enough space a NULL pointer is returned.
• General form
• ptr=(cast-type *) calloc(n, element-size);
• we
Prepared by: Moniruzzaman_CSE_KU_190231
free( ); Releasing the used space
• With dynamic run-time allocation, we need to release the space when it is not
required
• free(ptr);
• Frees previously allocated space created by malloc() or calloc()
Prepared by: Moniruzzaman_CSE_KU_190231
realloc( ); Altering the size of a block
• It is likely that the previous allocated memory is not sufficient and we need
additional space for more elements.
• It is also possible that the memory allocated is much larger than necessary and
we want to reduce it.
• ptr=realloc(ptr, newsize);
• Modifies the size of previously allocated space by malloc() or calloc().
Prepared by: Moniruzzaman_CSE_KU_190231
Linked List
• A list refers to a set of items organized sequentially
• Linked list is a completely different way to represent a list is to make each item
in the list part of a structure that also contains a “link” to the structure containing
the next item.
• A linked list is a dynamic data structures.
Prepared by: Moniruzzaman_CSE_KU_190231
Difference between array and linked list
Basic It is a consistent set of a fixed number of data
items.
It is an ordered set comprising a variable
number of data items.
Size Specified during declaration. No need to specify; grow and shrink during
execution
Storage
Allocation
Element location is allocated during compile
time.
Element position is assigned during run time.
Order of the
elements
Stored consecutively Stored randomly
Accessing the
element
Direct or randomly accessed, i.e., Specify the
array index or subscript.
Sequentially accessed, i.e., Traverse starting
from the first node in the list by the pointer.
Array Linked List
Prepared by: Moniruzzaman_CSE_KU_190231
Difference between array and linked list
Insertion and
deletion of
element
Slow relatively as shifting is required. Easier, fast and efficient.
Searching Binary search and linear search linear search
Memory
required
less More
Memory
Utilization
Ineffective Efficient
Array Linked List
Prepared by: Moniruzzaman_CSE_KU_190231
Advantages of linked list
• Can grow or shrink in size during the execution of a program
• Does not waste memory space
• Here it is not necessary to specify the number of nodes to be used in the list
• It provides flexibility is allowing the items to be rearranged efficiently
• It is easier to insert or delete items by rearranging the links
Prepared by: Moniruzzaman_CSE_KU_190231
Limitation of Linked List
• The access to any arbitrary item is little cumbersome and time consuming.
• Use more storage than an array with the same number of items. This is because
each item has an additional link field.
• Linked lists are traversed in unidirection
• Complex to implement
• Sequential access to elements
• Leads to memory problems if not taken care about the pointer manipulations
properly
That is, Whenever we deal with a fixed length list, it would be better to use an array
rather than a linked list.
Prepared by: Moniruzzaman_CSE_KU_190231
Types of linked list:
Prepared by: Moniruzzaman_CSE_KU_190231
We need basic of pointer
Initiation :
pointer ptr contains the address of a variable
reference variable *ptr contains denotes the value of variables
int i;
int *j;
i=5;
j=&i;
*j= ? ans: 5
j= ? ans: 65524
p=&x;
p points to x
q=&y;
q points to y
Prepared by: Moniruzzaman_CSE_KU_190231
We need basic of pointer
Initialization: Assignment p=q
p=&x; 100 p=q; 100
p x p x
q=&y; 200 200
q y q y
*p=100 and *q=200 and p< >q *p=*q=200 but x< >y
Assignment *p=*q NULL pointers
*p=*q; 200 p=0; (or p= NULL;) p 0
p x p x
200 q=0; (or q=NULL;) q 0
q y
x=y=200 but p< >q p and q points nothing
Prepared by: Moniruzzaman_CSE_KU_190231
What we can do with Linked List:
• Creating a list
• Traversing the list
• Counting the items in the list
• Printing the list (or sub list)
• Looking up an item for editing or printing
• Inserting an item
• Deleting an item
• Concatenating two lists
Prepared by: Moniruzzaman_CSE_KU_190231
What we can do with Linked List:
• Replace() : replaces a value stored at a position with some other value.
• Swap() : swap the values of the nodes specified by two positions.
• Merging two linked lists into a larger list
• Searching for an element in a linked list
• Reversing a linked list
Prepared by: Moniruzzaman_CSE_KU_190231
Program: (creating a linked list) Singly_1
#include<stdio.h>
#include<stdlib.h>
void createList(int);
struct node
{
int data;
struct node *right;
} *start=NULL, *end;
//typedef node x; // node type defined
//x *start=0, *end; //start r head 1
int main( )
{
int x;
printf("Enter the no. of data: ");
createList(x);
return 0;
}
Prepared by: Moniruzzaman_CSE_KU_190231
Program: (creating a linked list) Singly_2
void createList(int x) {
int i, num;
struct node *newNode ;
if(x>=1){
start = (struct node*)malloc(sizeof(struct node));
if(start!=NULL){
printf(“Enter data for node 1: ”);
scanf(“%d”,&num);
start->data=num;
start->right=NULL;
end = start;
for(i=2 ; i<=x ; i++){
newNode = (struct node*)malloc (sizeof(struct node));
if(newNode!=NULL){
Prepared by: Moniruzzaman_CSE_KU_190231
Program: (creating a linked list) Singly_3
printf(“Enter data for node %d: ”,i);
scanf(“%d”, &num);
newNode->data = num;
newNode->right = NULL;
end->right = newNode;
end = newNode;
}
else{
printf(“Memory not allocated”);
break;
}
}
}
else{
printf(“Memory not allocated”);
}
}
}
Prepared by: Moniruzzaman_CSE_KU_190231
Program: (creating a linked list) Doubly_1
#include<stdio.h> //same as singly changes shown in red text
#include<stdlib.h>
void createList(int);
struct node
{
int data;
struct node *right;
struct node *left;
} *start=NULL, *end=NULL;
//typedef node x; // node type defined
//x *start=0, *end; //start r head 1
int main( )
{
int x;
printf("Enter the no. of data: ");
while (scanf("%d",&x))
createList(x);
return 0;
}
Prepared by: Moniruzzaman_CSE_KU_190231
Program: (creating a linked list) Doubly_2
void createList(int x) { //same as singly changes shown in red text
int i, num;
struct node *newNode ;
if(x>=1){
start = (struct node*)malloc(sizeof(struct node));
if(start!=NULL){
printf(“Enter data for node 1: ”);
scanf(“%d”,&num);
start->data=num;
start->right=NULL;
start->left=NULL;
end = start;
for(i=2 ; i<=x ; i++){
newNode = (struct node*)malloc (sizeof(struct node));
if(newNode!=NULL){
Prepared by: Moniruzzaman_CSE_KU_190231
Program: (creating a linked list) Doubly_3
printf(“Enter data for node %d: ”,i);
scanf(“%d”, &num);
newNode->data = num;
newNode-> left = end;
newNode->right = NULL;
end->right = newNode;
end = newNode;
}
else{
printf(“Memory not allocated”);
break;
}
}
}
else{
printf(“Memory not allocated”);
}
}
}
Prepared by: Moniruzzaman_CSE_KU_190231
Program: (printing/traversing a linked list)
//Let start denotes the first node of the list
#include<stdio.h> // Singly or doubly are same
#include<stdlib.h>
Void display( );
struct node{
int data;
struct node *right;
} *temp;
Int main( ){
display( );
return 0;
}
void displayList(){
int i=1;
temp=start;
while(temp!=NULL){
printf("Node_%d: %dn",i,temp->data);
i++;
temp=temp->right;
}
} Prepared by: Moniruzzaman_CSE_KU_190231
Program: Checking an item in Linked List
void check(){ // Singly or doubly are same
int lf, count=0, pos=0; //1st er oi main() r struct j kono ans e likhte hobe
printf("nWhat you want to search? ");
scanf("%d",&lf);
p = start;
while (p!= NULL){
pos++;
if(p->data==lf){
printf("n%d is in position %dn", lf , pos);
p=p->right;
count++ ;
}
else{
p=p->right;
}
}
if(count==0){
printf("Given data doesn't exist");
}
}
Prepared by: Moniruzzaman_CSE_KU_190231
Program: Replace of any data
void editData(){ // Singly or doubly are same
int old,new, count=0; //1st er oi main() r struct j kono ans e likte hobe
printf("Enter the old data: ");
scanf("%d",&old);
printf("Enter the new data: ");
scanf("%d",&new);
p=start;
while(p!=NULL){
if (p->data!=old){
p=p->right;
}
else{
p->data = new;
p=p->right;
count++;
}
}
if(count==0){
printf("The given data doesn't exist in the list");
}
}
Prepared by: Moniruzzaman_CSE_KU_190231
Program: Counting data in a linked list
//Let start denotes the first node of the list
#include<stdio.h> // Singly or doubly are same
#include<stdlib.h>
Void countData( );
struct node{
int data;
struct node *right;
} *temp;
Int main( ){
countData( );
return 0;
}
void countData(){
int count=0;
temp=start;
while(temp!=NULL){
count++;
temp=temp->right;
}
printf(“No. of Data: %d”, count);
} Prepared by: Moniruzzaman_CSE_KU_190231
Program: Inserting node in a linked list_1
//Let start denotes the first node of the list
#include<stdio.h> // Singly or doubly are same
#include<stdlib.h> //red code for making doubly
void insertFirst( int);
Void insertLast(int );
Void insertMiddle(int );
struct node{
int data;
struct node *right, *left;
} *temp;
Int main( ){
int newData, position;
printf("Enter the new data");
scanf("%d",&newData);
printf("Enter the position");
scanf("%d",&position);
switch(position){
case 1: {
Prepared by: Moniruzzaman_CSE_KU_190231
Program: Inserting node in a linked list_2
insertFirst(newData);
break; //red code for making doubly
}
case 2: {
insertLast(newData);
break ;
}
case 3: {
insertMiddle(newData);
break;
}
default: exit(0);
}
}
void insertFirst(int x){
struct node *newInsert = (struct node *)malloc(sizeof(struct node));
newInsert->data=x;
newInsert->right=start;
newInsert->left = NULL;
start=newInsert;
} Prepared by: Moniruzzaman_CSE_KU_190231
Program: Inserting node in a linked list_3
void insertLast(int x){ //red code for making doubly
struct node *newInsert = (struct node *)malloc(sizeof(struct node));
newInsert->data=x;
newInsert->right=NULL;
newInsert->left = end;
end->right = newInsert;
end=newInsert;
}
void insertMiddle(int x) {
int pos, count=1;
printf(“Enter the exact position”);
scanf(“%d”,&pos);
struct node *newInsert, *temp;
newInsert = (struct node *)malloc(sizeof(struct node));
temp=start;
while(temp!=NULLL && count!=pos-1){
temp= temp->right;
count++
}
Prepared by: Moniruzzaman_CSE_KU_190231
Program: Inserting node in a linked list_4
newInsert->data= x ; //red code for making doubly
newInsert->right= temp->right ;
newInsert->left = temp ;
temp-> right = newInsert ;
newInsert->right->left = newInsert; //newInsert->right ei tuku jeta add korbo
} //tar porer node indicate kore r tar->left
//Diagram:
Prepared by: Moniruzzaman_CSE_KU_190231
Program: Deleting a node from linked list_1
//Let ‘start’ denotes the first node of the list
//Let ‘end’ denotes the last node of the list
#include<stdio.h> // Singly or doubly are same
#include<stdlib.h> //red code for making doubly
void deleteFirst( );
Void deleteLast( );
Void deleteSpecific( );
struct node{
int data;
struct node *right, *left;
} *temp;
Int main( ){
int position;
printf(“press 1 to delete from first, 2 for last and 3 for specific positoin");
scanf("%d",&position);
switch(position){
case 1: {
Prepared by: Moniruzzaman_CSE_KU_190231
Program: Deleting a node from linked list_2
deleteFirst( );
break; //red code for making doubly
}
case 2: {
deleteLast( );
break ;
}
case 3: {
deleteSpecific(newData);
break;
}
default: exit(0);
}
}
void deleteFirst( ){
temp=start;
start= start->right;
start->left = NULL;
free(temp);
}
Prepared by: Moniruzzaman_CSE_KU_190231
Program: Deleting a node from linked list_3
void deleteLast( ){ //same code for making doubly
struct node *prev; //and also have a very simple way
temp = start;
while (temp->right!=NULL){ void deleteLast( ){
prev = temp; temp = start;
temp = temp -> right; while(temp->right !=NULL){
} temp=temp->right;
if(temp==head){ }
head=NULL; temp->left->right= NULL;
} free(temp);
else{ }
prev->right = NULL;
}
free(temp);
}
Prepared by: Moniruzzaman_CSE_KU_190231
Program: Deleting a node from linked list_4
void deleteSpecific( ) { //red code for making doubly
int pos, count=1;
struct node *prev;
printf(“Enter the deleting position”);
scanf(“%d”,&pos);
temp=start;
while(count!=pos){
prev=temp;
temp= temp->right;
count++;
}
prev->right= temp->right;
temp->right->left = prev;
free(temp);
}
Prepared by: Moniruzzaman_CSE_KU_190231
Merge of 2 linked list:
void merge(struct node *start1, struct node *start2){
struct node *temp;
temp= start1;
while(temp->right != NULL){
temp=temp->right;
}
temp-right = start2;
}
Reversed the linked list:
void reverse ( ){
struct node *current, *next, *prev;
current = start;
prev = NULL;
while(current != NULL){
next=current->right;
current->right = prev;
prev = current;
current = next;
}
star= prev;
}

More Related Content

What's hot

What's hot (19)

Linked list
Linked listLinked list
Linked list
 
single linked list
single linked listsingle linked list
single linked list
 
Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.ppt
 
Linklist
LinklistLinklist
Linklist
 
header, circular and two way linked lists
header, circular and two way linked listsheader, circular and two way linked lists
header, circular and two way linked lists
 
Linked list
Linked listLinked list
Linked list
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked Lists
 
Linked lists
Linked listsLinked lists
Linked lists
 
Operations on linked list
Operations on linked listOperations on linked list
Operations on linked list
 
Linked List
Linked ListLinked List
Linked List
 
Linked list
Linked listLinked list
Linked list
 
Linked list
Linked listLinked list
Linked list
 
Singly & Circular Linked list
Singly & Circular Linked listSingly & Circular Linked list
Singly & Circular Linked list
 
Link List
Link ListLink List
Link List
 
Data Structures with C Linked List
Data Structures with C Linked ListData Structures with C Linked List
Data Structures with C Linked List
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
 
Deletion from single way linked list and search
Deletion from single way linked list and searchDeletion from single way linked list and search
Deletion from single way linked list and search
 
Linked list
Linked listLinked list
Linked list
 
358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8
 

Similar to Dynamic memory allocation

Dynamic memory allocation and linked lists
Dynamic memory allocation and linked listsDynamic memory allocation and linked lists
Dynamic memory allocation and linked listsDeepam Aggarwal
 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptxjack881
 
Data Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptxData Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptxGIRISHKUMARBC1
 
Funddamentals of data structures
Funddamentals of data structuresFunddamentals of data structures
Funddamentals of data structuresGlobalidiots
 
Linked list using Dynamic Memory Allocation
Linked list using Dynamic Memory AllocationLinked list using Dynamic Memory Allocation
Linked list using Dynamic Memory Allocationkiran Patel
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxssuser688516
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxVeerannaKotagi1
 
Data structure and algorithms chapter three LINKED LIST
Data structure and algorithms chapter three LINKED LISTData structure and algorithms chapter three LINKED LIST
Data structure and algorithms chapter three LINKED LISTbinakasehun2026
 
Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Getachew Ganfur
 
Data structure
Data structureData structure
Data structureNida Ahmed
 
Coding - L30-L31-Array of structures.pptx
Coding - L30-L31-Array of structures.pptxCoding - L30-L31-Array of structures.pptx
Coding - L30-L31-Array of structures.pptxhappycocoman
 

Similar to Dynamic memory allocation (20)

Dynamic memory allocation and linked lists
Dynamic memory allocation and linked listsDynamic memory allocation and linked lists
Dynamic memory allocation and linked lists
 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptx
 
Data Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptxData Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptx
 
Introduction linked list
Introduction linked listIntroduction linked list
Introduction linked list
 
Funddamentals of data structures
Funddamentals of data structuresFunddamentals of data structures
Funddamentals of data structures
 
Linked list using Dynamic Memory Allocation
Linked list using Dynamic Memory AllocationLinked list using Dynamic Memory Allocation
Linked list using Dynamic Memory Allocation
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
 
Unit II Data Structure 2hr topic - List - Operations.pptx
Unit II  Data Structure 2hr topic - List - Operations.pptxUnit II  Data Structure 2hr topic - List - Operations.pptx
Unit II Data Structure 2hr topic - List - Operations.pptx
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
 
C1320prespost
C1320prespostC1320prespost
C1320prespost
 
Data structure and algorithms chapter three LINKED LIST
Data structure and algorithms chapter three LINKED LISTData structure and algorithms chapter three LINKED LIST
Data structure and algorithms chapter three LINKED LIST
 
lect 2-DS ALGO(online).pdf
lect 2-DS  ALGO(online).pdflect 2-DS  ALGO(online).pdf
lect 2-DS ALGO(online).pdf
 
linkedLists.ppt
linkedLists.pptlinkedLists.ppt
linkedLists.ppt
 
Unit 5 linked list
Unit   5 linked listUnit   5 linked list
Unit 5 linked list
 
Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02
 
DSModule2.pptx
DSModule2.pptxDSModule2.pptx
DSModule2.pptx
 
Data structure
Data structureData structure
Data structure
 
Unit v
Unit vUnit v
Unit v
 
Coding - L30-L31-Array of structures.pptx
Coding - L30-L31-Array of structures.pptxCoding - L30-L31-Array of structures.pptx
Coding - L30-L31-Array of structures.pptx
 
Struct
StructStruct
Struct
 

Recently uploaded

"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...Erbil Polytechnic University
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfChristianCDAM
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 
Configuration of IoT devices - Systems managament
Configuration of IoT devices - Systems managamentConfiguration of IoT devices - Systems managament
Configuration of IoT devices - Systems managamentBharaniDharan195623
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
BSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptxBSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptxNiranjanYadav41
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptNarmatha D
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solidnamansinghjarodiya
 
Risk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectRisk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectErbil Polytechnic University
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdfHafizMudaserAhmad
 
DM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in projectDM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in projectssuserb6619e
 
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Erbil Polytechnic University
 

Recently uploaded (20)

"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdf
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 
Configuration of IoT devices - Systems managament
Configuration of IoT devices - Systems managamentConfiguration of IoT devices - Systems managament
Configuration of IoT devices - Systems managament
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
BSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptxBSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptx
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.ppt
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solid
 
Risk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectRisk Management in Engineering Construction Project
Risk Management in Engineering Construction Project
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
DM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in projectDM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in project
 
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
 

Dynamic memory allocation

  • 1. Dynamic Memory Allocation & Linked Lists Prepared by: Moniruzzaman_CSE_KU_190231
  • 2. Dynamic memory location: • The process of allocating memory at run time is known as dynamic memory allocation. • C does not inherently have this facility. There are four library routines known as memory management functions that can be used for allocating and freeing memory during execution. • malloc(), calloc(), free(), realloc() • All are defined in alloc.h Prepared by: Moniruzzaman_CSE_KU_190231
  • 3. malloc: Allocating a block of memory • General form • ptr = (cast-type *) malloc(byte-size); • ptr is a pointer of type cast-type • The malloc() returns a pointer (of cast-type) to an area of memory with size byte-size. If there is not enough space a NULL pointer is returned. • Example • x=(int *) malloc(100*sizeof(int)); • cptr=(char *) malloc(10); • st= (struct *) malloc(sizeof(struct store)); • Storage space allocated dynamically has no name and therefore its contents can be accessed only through a pointer. Prepared by: Moniruzzaman_CSE_KU_190231
  • 4. calloc: Allocating multiple block of memory • While malloc() allocates a single block of storage space, calloc() allocates multiple blocks of storage, each of the same size, and then set all bytes to zero. If there is not enough space a NULL pointer is returned. • General form • ptr=(cast-type *) calloc(n, element-size); • we Prepared by: Moniruzzaman_CSE_KU_190231
  • 5. free( ); Releasing the used space • With dynamic run-time allocation, we need to release the space when it is not required • free(ptr); • Frees previously allocated space created by malloc() or calloc() Prepared by: Moniruzzaman_CSE_KU_190231
  • 6. realloc( ); Altering the size of a block • It is likely that the previous allocated memory is not sufficient and we need additional space for more elements. • It is also possible that the memory allocated is much larger than necessary and we want to reduce it. • ptr=realloc(ptr, newsize); • Modifies the size of previously allocated space by malloc() or calloc(). Prepared by: Moniruzzaman_CSE_KU_190231
  • 7. Linked List • A list refers to a set of items organized sequentially • Linked list is a completely different way to represent a list is to make each item in the list part of a structure that also contains a “link” to the structure containing the next item. • A linked list is a dynamic data structures. Prepared by: Moniruzzaman_CSE_KU_190231
  • 8. Difference between array and linked list Basic It is a consistent set of a fixed number of data items. It is an ordered set comprising a variable number of data items. Size Specified during declaration. No need to specify; grow and shrink during execution Storage Allocation Element location is allocated during compile time. Element position is assigned during run time. Order of the elements Stored consecutively Stored randomly Accessing the element Direct or randomly accessed, i.e., Specify the array index or subscript. Sequentially accessed, i.e., Traverse starting from the first node in the list by the pointer. Array Linked List Prepared by: Moniruzzaman_CSE_KU_190231
  • 9. Difference between array and linked list Insertion and deletion of element Slow relatively as shifting is required. Easier, fast and efficient. Searching Binary search and linear search linear search Memory required less More Memory Utilization Ineffective Efficient Array Linked List Prepared by: Moniruzzaman_CSE_KU_190231
  • 10. Advantages of linked list • Can grow or shrink in size during the execution of a program • Does not waste memory space • Here it is not necessary to specify the number of nodes to be used in the list • It provides flexibility is allowing the items to be rearranged efficiently • It is easier to insert or delete items by rearranging the links Prepared by: Moniruzzaman_CSE_KU_190231
  • 11. Limitation of Linked List • The access to any arbitrary item is little cumbersome and time consuming. • Use more storage than an array with the same number of items. This is because each item has an additional link field. • Linked lists are traversed in unidirection • Complex to implement • Sequential access to elements • Leads to memory problems if not taken care about the pointer manipulations properly That is, Whenever we deal with a fixed length list, it would be better to use an array rather than a linked list. Prepared by: Moniruzzaman_CSE_KU_190231
  • 12. Types of linked list: Prepared by: Moniruzzaman_CSE_KU_190231
  • 13. We need basic of pointer Initiation : pointer ptr contains the address of a variable reference variable *ptr contains denotes the value of variables int i; int *j; i=5; j=&i; *j= ? ans: 5 j= ? ans: 65524 p=&x; p points to x q=&y; q points to y Prepared by: Moniruzzaman_CSE_KU_190231
  • 14. We need basic of pointer Initialization: Assignment p=q p=&x; 100 p=q; 100 p x p x q=&y; 200 200 q y q y *p=100 and *q=200 and p< >q *p=*q=200 but x< >y Assignment *p=*q NULL pointers *p=*q; 200 p=0; (or p= NULL;) p 0 p x p x 200 q=0; (or q=NULL;) q 0 q y x=y=200 but p< >q p and q points nothing Prepared by: Moniruzzaman_CSE_KU_190231
  • 15. What we can do with Linked List: • Creating a list • Traversing the list • Counting the items in the list • Printing the list (or sub list) • Looking up an item for editing or printing • Inserting an item • Deleting an item • Concatenating two lists Prepared by: Moniruzzaman_CSE_KU_190231
  • 16. What we can do with Linked List: • Replace() : replaces a value stored at a position with some other value. • Swap() : swap the values of the nodes specified by two positions. • Merging two linked lists into a larger list • Searching for an element in a linked list • Reversing a linked list Prepared by: Moniruzzaman_CSE_KU_190231
  • 17. Program: (creating a linked list) Singly_1 #include<stdio.h> #include<stdlib.h> void createList(int); struct node { int data; struct node *right; } *start=NULL, *end; //typedef node x; // node type defined //x *start=0, *end; //start r head 1 int main( ) { int x; printf("Enter the no. of data: "); createList(x); return 0; } Prepared by: Moniruzzaman_CSE_KU_190231
  • 18. Program: (creating a linked list) Singly_2 void createList(int x) { int i, num; struct node *newNode ; if(x>=1){ start = (struct node*)malloc(sizeof(struct node)); if(start!=NULL){ printf(“Enter data for node 1: ”); scanf(“%d”,&num); start->data=num; start->right=NULL; end = start; for(i=2 ; i<=x ; i++){ newNode = (struct node*)malloc (sizeof(struct node)); if(newNode!=NULL){ Prepared by: Moniruzzaman_CSE_KU_190231
  • 19. Program: (creating a linked list) Singly_3 printf(“Enter data for node %d: ”,i); scanf(“%d”, &num); newNode->data = num; newNode->right = NULL; end->right = newNode; end = newNode; } else{ printf(“Memory not allocated”); break; } } } else{ printf(“Memory not allocated”); } } } Prepared by: Moniruzzaman_CSE_KU_190231
  • 20. Program: (creating a linked list) Doubly_1 #include<stdio.h> //same as singly changes shown in red text #include<stdlib.h> void createList(int); struct node { int data; struct node *right; struct node *left; } *start=NULL, *end=NULL; //typedef node x; // node type defined //x *start=0, *end; //start r head 1 int main( ) { int x; printf("Enter the no. of data: "); while (scanf("%d",&x)) createList(x); return 0; } Prepared by: Moniruzzaman_CSE_KU_190231
  • 21. Program: (creating a linked list) Doubly_2 void createList(int x) { //same as singly changes shown in red text int i, num; struct node *newNode ; if(x>=1){ start = (struct node*)malloc(sizeof(struct node)); if(start!=NULL){ printf(“Enter data for node 1: ”); scanf(“%d”,&num); start->data=num; start->right=NULL; start->left=NULL; end = start; for(i=2 ; i<=x ; i++){ newNode = (struct node*)malloc (sizeof(struct node)); if(newNode!=NULL){ Prepared by: Moniruzzaman_CSE_KU_190231
  • 22. Program: (creating a linked list) Doubly_3 printf(“Enter data for node %d: ”,i); scanf(“%d”, &num); newNode->data = num; newNode-> left = end; newNode->right = NULL; end->right = newNode; end = newNode; } else{ printf(“Memory not allocated”); break; } } } else{ printf(“Memory not allocated”); } } } Prepared by: Moniruzzaman_CSE_KU_190231
  • 23. Program: (printing/traversing a linked list) //Let start denotes the first node of the list #include<stdio.h> // Singly or doubly are same #include<stdlib.h> Void display( ); struct node{ int data; struct node *right; } *temp; Int main( ){ display( ); return 0; } void displayList(){ int i=1; temp=start; while(temp!=NULL){ printf("Node_%d: %dn",i,temp->data); i++; temp=temp->right; } } Prepared by: Moniruzzaman_CSE_KU_190231
  • 24. Program: Checking an item in Linked List void check(){ // Singly or doubly are same int lf, count=0, pos=0; //1st er oi main() r struct j kono ans e likhte hobe printf("nWhat you want to search? "); scanf("%d",&lf); p = start; while (p!= NULL){ pos++; if(p->data==lf){ printf("n%d is in position %dn", lf , pos); p=p->right; count++ ; } else{ p=p->right; } } if(count==0){ printf("Given data doesn't exist"); } } Prepared by: Moniruzzaman_CSE_KU_190231
  • 25. Program: Replace of any data void editData(){ // Singly or doubly are same int old,new, count=0; //1st er oi main() r struct j kono ans e likte hobe printf("Enter the old data: "); scanf("%d",&old); printf("Enter the new data: "); scanf("%d",&new); p=start; while(p!=NULL){ if (p->data!=old){ p=p->right; } else{ p->data = new; p=p->right; count++; } } if(count==0){ printf("The given data doesn't exist in the list"); } } Prepared by: Moniruzzaman_CSE_KU_190231
  • 26. Program: Counting data in a linked list //Let start denotes the first node of the list #include<stdio.h> // Singly or doubly are same #include<stdlib.h> Void countData( ); struct node{ int data; struct node *right; } *temp; Int main( ){ countData( ); return 0; } void countData(){ int count=0; temp=start; while(temp!=NULL){ count++; temp=temp->right; } printf(“No. of Data: %d”, count); } Prepared by: Moniruzzaman_CSE_KU_190231
  • 27. Program: Inserting node in a linked list_1 //Let start denotes the first node of the list #include<stdio.h> // Singly or doubly are same #include<stdlib.h> //red code for making doubly void insertFirst( int); Void insertLast(int ); Void insertMiddle(int ); struct node{ int data; struct node *right, *left; } *temp; Int main( ){ int newData, position; printf("Enter the new data"); scanf("%d",&newData); printf("Enter the position"); scanf("%d",&position); switch(position){ case 1: { Prepared by: Moniruzzaman_CSE_KU_190231
  • 28. Program: Inserting node in a linked list_2 insertFirst(newData); break; //red code for making doubly } case 2: { insertLast(newData); break ; } case 3: { insertMiddle(newData); break; } default: exit(0); } } void insertFirst(int x){ struct node *newInsert = (struct node *)malloc(sizeof(struct node)); newInsert->data=x; newInsert->right=start; newInsert->left = NULL; start=newInsert; } Prepared by: Moniruzzaman_CSE_KU_190231
  • 29. Program: Inserting node in a linked list_3 void insertLast(int x){ //red code for making doubly struct node *newInsert = (struct node *)malloc(sizeof(struct node)); newInsert->data=x; newInsert->right=NULL; newInsert->left = end; end->right = newInsert; end=newInsert; } void insertMiddle(int x) { int pos, count=1; printf(“Enter the exact position”); scanf(“%d”,&pos); struct node *newInsert, *temp; newInsert = (struct node *)malloc(sizeof(struct node)); temp=start; while(temp!=NULLL && count!=pos-1){ temp= temp->right; count++ } Prepared by: Moniruzzaman_CSE_KU_190231
  • 30. Program: Inserting node in a linked list_4 newInsert->data= x ; //red code for making doubly newInsert->right= temp->right ; newInsert->left = temp ; temp-> right = newInsert ; newInsert->right->left = newInsert; //newInsert->right ei tuku jeta add korbo } //tar porer node indicate kore r tar->left //Diagram: Prepared by: Moniruzzaman_CSE_KU_190231
  • 31. Program: Deleting a node from linked list_1 //Let ‘start’ denotes the first node of the list //Let ‘end’ denotes the last node of the list #include<stdio.h> // Singly or doubly are same #include<stdlib.h> //red code for making doubly void deleteFirst( ); Void deleteLast( ); Void deleteSpecific( ); struct node{ int data; struct node *right, *left; } *temp; Int main( ){ int position; printf(“press 1 to delete from first, 2 for last and 3 for specific positoin"); scanf("%d",&position); switch(position){ case 1: { Prepared by: Moniruzzaman_CSE_KU_190231
  • 32. Program: Deleting a node from linked list_2 deleteFirst( ); break; //red code for making doubly } case 2: { deleteLast( ); break ; } case 3: { deleteSpecific(newData); break; } default: exit(0); } } void deleteFirst( ){ temp=start; start= start->right; start->left = NULL; free(temp); } Prepared by: Moniruzzaman_CSE_KU_190231
  • 33. Program: Deleting a node from linked list_3 void deleteLast( ){ //same code for making doubly struct node *prev; //and also have a very simple way temp = start; while (temp->right!=NULL){ void deleteLast( ){ prev = temp; temp = start; temp = temp -> right; while(temp->right !=NULL){ } temp=temp->right; if(temp==head){ } head=NULL; temp->left->right= NULL; } free(temp); else{ } prev->right = NULL; } free(temp); } Prepared by: Moniruzzaman_CSE_KU_190231
  • 34. Program: Deleting a node from linked list_4 void deleteSpecific( ) { //red code for making doubly int pos, count=1; struct node *prev; printf(“Enter the deleting position”); scanf(“%d”,&pos); temp=start; while(count!=pos){ prev=temp; temp= temp->right; count++; } prev->right= temp->right; temp->right->left = prev; free(temp); } Prepared by: Moniruzzaman_CSE_KU_190231
  • 35. Merge of 2 linked list: void merge(struct node *start1, struct node *start2){ struct node *temp; temp= start1; while(temp->right != NULL){ temp=temp->right; } temp-right = start2; }
  • 36. Reversed the linked list: void reverse ( ){ struct node *current, *next, *prev; current = start; prev = NULL; while(current != NULL){ next=current->right; current->right = prev; prev = current; current = next; } star= prev; }