SlideShare a Scribd company logo
1 of 33
Dynamic Memory & Linked List
Prepared by: Afaq Mansoor Khan
BSSE III- Group A
Session 2017-21
IMSciences, Peshawar.
Last Lecture Summary
• Selection Sort,
• Insertion Sort,
• Algorithms Analysis
• Merge Sort Algorithm,
• Merge Sort Analysis
Objectives Overview
• Dynamic Memory Allocation
• Introduction to Linked List
4
Problem with Arrays
• Sometimes
▫ Amount of data cannot be predicted beforehand
▫ Number of data items keeps changing during program execution
• Example: Search for an element in an array of N elements
• One solution: find the maximum possible value of N and allocate an
array of N elements
▫ Wasteful of memory space, as N may be much smaller in some
executions
▫ Example: maximum value of N may be 10,000, but a particular
run may need to search only among 100 elements
 Using array of size 10,000 always wastes memory in most cases
Better Solution
• Dynamic memory allocation
▫ Know how much memory is needed after the program is
run
 Example: ask the user to enter from keyboard
▫ Dynamically allocate only the amount of memory needed
5
Memory Allocation
There are essentially two types of memory allocation
1. Static
2. Dynamic
Memory Allocation - Static
Static – Done by the compiler automatically (implicitly).
o Global variables or objects -- memory is allocated at the start
of the program, and freed when program exits; alive
throughout program execution
1. Can be access anywhere in the program.
o Local variables (inside a routine) – memory is allocated when
the routine starts and freed when the routine returns.
1. A local variable cannot be accessed from another routine.
o Allocation and free are done implicitly.
o No need to explicitly manage memory is nice, but has
limitations!
1. Using static allocation, the array size must be fixed.
Memory Allocation - Dynamic
Wouldn’t it be nice to be able to have an array whose
size can be adjusted depending on needs.
Dynamic memory allocation deals with this situation.
Dynamic – Done explicitly by programmer.
Programmer explicitly requests the system to allocate
memory and return starting address of memory allocated
(what is this?). This address can be used by the
programmer to access the allocated memory.
When done using memory, it must be explicitly freed.
Explicitly allocating memory in C++:
The ‘new’ Operator
• Used to dynamically allocate memory
• Can be used to allocate a single variable/object or an
array of variables/objects
• The new operator returns pointer to the type
allocated
• Before the assignment, the pointer may or may not
point to a legitimate memory
• After the assignment, the pointer points to a
legitimate memory.
Explicitly freeing memory in C++:
The ‘delete’ Operator
• Used to free memory allocated with new operator
• The delete operator should be called on a pointer to
dynamically allocated memory when it is no longer needed
• Can delete a single variable/object or an array
delete PointerName;
delete [] ArrayName;
• After delete is called on a memory region, that region should
no longer be accessed by the program
• Convention is to set pointer to deleted memory to NULL
Any new must have a corresponding delete --- if not, the
program has memory leak.
New and delete may not be in the same routine.
Example
• int main()
• {
• // Below variables are allocated memory
• // dynamically.
• int *ptr1 = new int;
• int *ptr2 = new int[10];
•
• // Dynamically allocated memory is
• // deallocated
• delete ptr1;
• delete [] ptr2;
• }
The Heap
• Large area of memory controlled by the runtime
system that is used to grant dynamic memory
requests.
• It is possible to allocate memory and “lose” the
pointer to that region without freeing it. This is
called a memory leak.
• A memory leak can cause the heap to become full
• If an attempt is made to allocate memory from the
heap and there is not enough, an exception is
generated (error)
Why use dynamic memory allocation?
• Allows data (especially arrays) to take on variable
sizes (e.g. ask the user how many numbers to store,
then generate an array of integers exactly that size).
• Allows locally created variables to live past end of
routine.
• Allows us to create many structures used in Data
Structures and Algorithms
The . and -> operators
• The dot operator is used to access an object’s members
▫ M1.Simplify();
▫ M1.num = 5;
• But how do we access an objects members if we only
have a pointer to the object?
• If we have M1_ptr = &M1, Perhaps we would use
(*(M1_ptr)).Simplify()
• A shorthand for this is the arrow operator
• M1_ptr->Simplify() is equivalent to(*(M1_ptr)).Simplify()
Introduction to Linked Lists
Linked Lists
• Linked List is a very commonly used linear data
structure which consists of group of nodes in a
sequence.
• Each node holds its own data and the address of the
next node hence forming a chain like structure.
• Linked Lists are used to create trees and graphs.
Linked List Representation
Types of Linked Lists
There are 3 different implementations of Linked List
available, they are:
1. Singly Linked List
2. Doubly Linked List
3. Circular Linked List
Singly Linked List
• Singly linked lists contain nodes which have a data
part as well as an address part i.e. next, which points
to the next node in the sequence of nodes.
• The operations we can perform on singly linked lists
are insertion, deletion and traversal.
Doubly Linked List
• In a doubly linked list, each node contains a data part
and two addresses, one for the previous node and
one for the next node.
Circular Linked List
• In circular linked list the last node of the list holds
the address of the first node hence forming a circular
chain.
Advantages of Linked Lists
• They are a dynamic in nature which allocates the
memory when required.
• Insertion and deletion operations can be easily
implemented.
• Linked List reduces the access time.
Disadvantages of Linked Lists
• The memory is wasted as pointers require extra
memory for storage.
• No element can be accessed randomly; it has to
access each node sequentially.
• Reverse Traversing is difficult in linked list.
• Not cache friendly. Since array elements are
contiguous locations, there is locality of reference
which is not there in case of linked lists.
Applications of Linked Lists
• Linked lists are used to implement stacks, queues,
graphs, etc. Linked lists let you insert elements at the
beginning and end of the list. In Linked Lists we don't
need to know the size in advance
Array vs Linked List
• Both Linked List and Array are used to store linear
data of similar type, but an array consumes
contiguous memory locations allocated at compile
time, i.e. at the time of declaration of array, while for
a linked list, memory is assigned as and when data is
added to it, which means at runtime.
On the left, we have Array and on the right, we have
Linked List.
Summary
• Dynamic Memory Allocation
▫ New Operator
▫ Delete Operator
▫ Heap
▫ dot . and -> operators
• Introduction to Linked List
▫ Types
▫ Advantages
▫ Disadvantages
▫ Applications
▫ Difference between Array and Linked List
References
• https://www.geeksforgeeks.org/what-is-dynamic-
memory-allocation/
• https://www.geeksforgeeks.org/new-and-delete-
operators-in-cpp-for-dynamic-memory/
• https://www.youtube.com/watch?v=texoDnnzWao
• https://www.studytonight.com/data-
structures/introduction-to-linked-list
• https://www.geeksforgeeks.org/linked-list-set-1-
introduction/

More Related Content

What's hot

DATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTESDATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTESAniruddha Paul
 
Introduction of data structure
Introduction of data structureIntroduction of data structure
Introduction of data structureeShikshak
 
Cupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithmCupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithmTarikuDabala1
 
Data structure lecture 2
Data structure lecture 2Data structure lecture 2
Data structure lecture 2Kumar
 
Chapter 2.2 data structures
Chapter 2.2 data structuresChapter 2.2 data structures
Chapter 2.2 data structuressshhzap
 
Data Structure and Algorithms
Data Structure and Algorithms Data Structure and Algorithms
Data Structure and Algorithms ManishPrajapati78
 
Data structure and algorithm notes
Data structure and algorithm notesData structure and algorithm notes
Data structure and algorithm notessuman khadka
 
Applications of data structures
Applications of data structuresApplications of data structures
Applications of data structuresWipro
 
Introduction to datastructure and algorithm
Introduction to datastructure and algorithmIntroduction to datastructure and algorithm
Introduction to datastructure and algorithmPratik Mota
 
Algorithm Complexity and Main Concepts
Algorithm Complexity and Main ConceptsAlgorithm Complexity and Main Concepts
Algorithm Complexity and Main ConceptsAdelina Ahadova
 
Elementary data structure
Elementary data structureElementary data structure
Elementary data structureBiswajit Mandal
 
PYTHON FULL TUTORIAL WITH PROGRAMMS
PYTHON FULL TUTORIAL WITH PROGRAMMSPYTHON FULL TUTORIAL WITH PROGRAMMS
PYTHON FULL TUTORIAL WITH PROGRAMMSAniruddha Paul
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithmsiqbalphy1
 
Data structure and algorithm
Data structure and algorithmData structure and algorithm
Data structure and algorithmTrupti Agrawal
 

What's hot (20)

Data Structure and Algorithms
Data Structure and AlgorithmsData Structure and Algorithms
Data Structure and Algorithms
 
DATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTESDATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTES
 
Introduction of data structure
Introduction of data structureIntroduction of data structure
Introduction of data structure
 
Cupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithmCupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithm
 
Data structure lecture 2
Data structure lecture 2Data structure lecture 2
Data structure lecture 2
 
Chapter 2.2 data structures
Chapter 2.2 data structuresChapter 2.2 data structures
Chapter 2.2 data structures
 
Lecture 1 and 2
Lecture 1 and 2Lecture 1 and 2
Lecture 1 and 2
 
Data Structure and Algorithms
Data Structure and Algorithms Data Structure and Algorithms
Data Structure and Algorithms
 
Data structures
Data structuresData structures
Data structures
 
Data structure and algorithm notes
Data structure and algorithm notesData structure and algorithm notes
Data structure and algorithm notes
 
Applications of data structures
Applications of data structuresApplications of data structures
Applications of data structures
 
Introduction to datastructure and algorithm
Introduction to datastructure and algorithmIntroduction to datastructure and algorithm
Introduction to datastructure and algorithm
 
Big o notation
Big o notationBig o notation
Big o notation
 
Algorithm Complexity and Main Concepts
Algorithm Complexity and Main ConceptsAlgorithm Complexity and Main Concepts
Algorithm Complexity and Main Concepts
 
Elementary data structure
Elementary data structureElementary data structure
Elementary data structure
 
PYTHON FULL TUTORIAL WITH PROGRAMMS
PYTHON FULL TUTORIAL WITH PROGRAMMSPYTHON FULL TUTORIAL WITH PROGRAMMS
PYTHON FULL TUTORIAL WITH PROGRAMMS
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
U nit i data structure-converted
U nit   i data structure-convertedU nit   i data structure-converted
U nit i data structure-converted
 
Data structure and algorithm
Data structure and algorithmData structure and algorithm
Data structure and algorithm
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
 

Similar to Dynamic Memory & Linked Lists

linked_list.pdf [for undergraduate students
linked_list.pdf [for undergraduate studentslinked_list.pdf [for undergraduate students
linked_list.pdf [for undergraduate studentsSazzadulIslam42
 
Heap Memory Management.pptx
Heap Memory Management.pptxHeap Memory Management.pptx
Heap Memory Management.pptxViji B
 
b,Sc it data structure.ppt
b,Sc it data structure.pptb,Sc it data structure.ppt
b,Sc it data structure.pptclassall
 
DS Module1 (1).pptx
DS Module1 (1).pptxDS Module1 (1).pptx
DS Module1 (1).pptxAnuJoseph95
 
b,Sc it data structure.pptx
b,Sc it data structure.pptxb,Sc it data structure.pptx
b,Sc it data structure.pptxclassall
 
b,Sc it data structure.pptx
b,Sc it data structure.pptxb,Sc it data structure.pptx
b,Sc it data structure.pptxclassall
 
Data Structure & Algorithm.pptx
Data Structure & Algorithm.pptxData Structure & Algorithm.pptx
Data Structure & Algorithm.pptxMumtaz
 
Unit 2 linear data structures
Unit 2   linear data structuresUnit 2   linear data structures
Unit 2 linear data structuresSenthil Murugan
 
Data Structure # vpmp polytechnic
Data Structure # vpmp polytechnicData Structure # vpmp polytechnic
Data Structure # vpmp polytechniclavparmar007
 
4 memory management bb
4   memory management bb4   memory management bb
4 memory management bbShahid Riaz
 
Data structures and algorithms Module-1.pdf
Data structures and algorithms Module-1.pdfData structures and algorithms Module-1.pdf
Data structures and algorithms Module-1.pdfDukeCalvin
 
1. Data structures introduction
1. Data structures introduction1. Data structures introduction
1. Data structures introductionMandeep Singh
 
Lecture 15 run timeenvironment_2
Lecture 15 run timeenvironment_2Lecture 15 run timeenvironment_2
Lecture 15 run timeenvironment_2Iffat Anjum
 
ADS Introduction
ADS IntroductionADS Introduction
ADS IntroductionNagendraK18
 

Similar to Dynamic Memory & Linked Lists (20)

linked_list.pdf [for undergraduate students
linked_list.pdf [for undergraduate studentslinked_list.pdf [for undergraduate students
linked_list.pdf [for undergraduate students
 
Heap Memory Management.pptx
Heap Memory Management.pptxHeap Memory Management.pptx
Heap Memory Management.pptx
 
b,Sc it data structure.ppt
b,Sc it data structure.pptb,Sc it data structure.ppt
b,Sc it data structure.ppt
 
DS Module1 (1).pptx
DS Module1 (1).pptxDS Module1 (1).pptx
DS Module1 (1).pptx
 
b,Sc it data structure.pptx
b,Sc it data structure.pptxb,Sc it data structure.pptx
b,Sc it data structure.pptx
 
b,Sc it data structure.pptx
b,Sc it data structure.pptxb,Sc it data structure.pptx
b,Sc it data structure.pptx
 
Data Structure & Algorithm.pptx
Data Structure & Algorithm.pptxData Structure & Algorithm.pptx
Data Structure & Algorithm.pptx
 
Unit 2 linear data structures
Unit 2   linear data structuresUnit 2   linear data structures
Unit 2 linear data structures
 
memory
memorymemory
memory
 
Cache Memory.pptx
Cache Memory.pptxCache Memory.pptx
Cache Memory.pptx
 
dsa.pptx
dsa.pptxdsa.pptx
dsa.pptx
 
Stack and heap
Stack and heapStack and heap
Stack and heap
 
lecture 02.2.ppt
lecture 02.2.pptlecture 02.2.ppt
lecture 02.2.ppt
 
Data Structure # vpmp polytechnic
Data Structure # vpmp polytechnicData Structure # vpmp polytechnic
Data Structure # vpmp polytechnic
 
4 memory management bb
4   memory management bb4   memory management bb
4 memory management bb
 
Data structures and algorithms Module-1.pdf
Data structures and algorithms Module-1.pdfData structures and algorithms Module-1.pdf
Data structures and algorithms Module-1.pdf
 
1. Data structures introduction
1. Data structures introduction1. Data structures introduction
1. Data structures introduction
 
Standard template library
Standard template libraryStandard template library
Standard template library
 
Lecture 15 run timeenvironment_2
Lecture 15 run timeenvironment_2Lecture 15 run timeenvironment_2
Lecture 15 run timeenvironment_2
 
ADS Introduction
ADS IntroductionADS Introduction
ADS Introduction
 

More from Afaq Mansoor Khan

Feature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingFeature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingAfaq Mansoor Khan
 
Role of Electronic Media in Pakistan
Role of Electronic Media in PakistanRole of Electronic Media in Pakistan
Role of Electronic Media in PakistanAfaq Mansoor Khan
 
Agile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAgile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAfaq Mansoor Khan
 
Ethical Hacking - An Overview
Ethical Hacking - An OverviewEthical Hacking - An Overview
Ethical Hacking - An OverviewAfaq Mansoor Khan
 
Software Architecture Design Decisions
Software Architecture Design DecisionsSoftware Architecture Design Decisions
Software Architecture Design DecisionsAfaq Mansoor Khan
 
Software Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinSoftware Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinAfaq Mansoor Khan
 
.Physics presentation - Asteroids
.Physics presentation - Asteroids.Physics presentation - Asteroids
.Physics presentation - AsteroidsAfaq Mansoor Khan
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsAfaq Mansoor Khan
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked ListsAfaq Mansoor Khan
 
Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & DeletionAfaq Mansoor Khan
 

More from Afaq Mansoor Khan (19)

Feature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingFeature Selection - Natural Language Processing
Feature Selection - Natural Language Processing
 
WiFi vs LiFi - A Comparison
WiFi vs LiFi - A ComparisonWiFi vs LiFi - A Comparison
WiFi vs LiFi - A Comparison
 
Role of Electronic Media in Pakistan
Role of Electronic Media in PakistanRole of Electronic Media in Pakistan
Role of Electronic Media in Pakistan
 
Agile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAgile Testing - Approach and Strategies
Agile Testing - Approach and Strategies
 
Ethical Hacking - An Overview
Ethical Hacking - An OverviewEthical Hacking - An Overview
Ethical Hacking - An Overview
 
Software Architecture Design Decisions
Software Architecture Design DecisionsSoftware Architecture Design Decisions
Software Architecture Design Decisions
 
How to Design an Algorithm
How to Design an AlgorithmHow to Design an Algorithm
How to Design an Algorithm
 
Software Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinSoftware Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and Linkedin
 
Quick sort
Quick sortQuick sort
Quick sort
 
.Physics presentation - Asteroids
.Physics presentation - Asteroids.Physics presentation - Asteroids
.Physics presentation - Asteroids
 
Graph Data Structure
Graph Data StructureGraph Data Structure
Graph Data Structure
 
AVL Tree Data Structure
AVL Tree Data StructureAVL Tree Data Structure
AVL Tree Data Structure
 
Binary tree
Binary treeBinary tree
Binary tree
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix Notations
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked Lists
 
Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & Deletion
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 

Recently uploaded

MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 

Recently uploaded (20)

MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 

Dynamic Memory & Linked Lists

  • 1. Dynamic Memory & Linked List Prepared by: Afaq Mansoor Khan BSSE III- Group A Session 2017-21 IMSciences, Peshawar.
  • 2. Last Lecture Summary • Selection Sort, • Insertion Sort, • Algorithms Analysis • Merge Sort Algorithm, • Merge Sort Analysis
  • 3. Objectives Overview • Dynamic Memory Allocation • Introduction to Linked List
  • 4. 4 Problem with Arrays • Sometimes ▫ Amount of data cannot be predicted beforehand ▫ Number of data items keeps changing during program execution • Example: Search for an element in an array of N elements • One solution: find the maximum possible value of N and allocate an array of N elements ▫ Wasteful of memory space, as N may be much smaller in some executions ▫ Example: maximum value of N may be 10,000, but a particular run may need to search only among 100 elements  Using array of size 10,000 always wastes memory in most cases
  • 5. Better Solution • Dynamic memory allocation ▫ Know how much memory is needed after the program is run  Example: ask the user to enter from keyboard ▫ Dynamically allocate only the amount of memory needed 5
  • 6. Memory Allocation There are essentially two types of memory allocation 1. Static 2. Dynamic
  • 7. Memory Allocation - Static Static – Done by the compiler automatically (implicitly). o Global variables or objects -- memory is allocated at the start of the program, and freed when program exits; alive throughout program execution 1. Can be access anywhere in the program. o Local variables (inside a routine) – memory is allocated when the routine starts and freed when the routine returns. 1. A local variable cannot be accessed from another routine. o Allocation and free are done implicitly. o No need to explicitly manage memory is nice, but has limitations! 1. Using static allocation, the array size must be fixed.
  • 8. Memory Allocation - Dynamic Wouldn’t it be nice to be able to have an array whose size can be adjusted depending on needs. Dynamic memory allocation deals with this situation. Dynamic – Done explicitly by programmer. Programmer explicitly requests the system to allocate memory and return starting address of memory allocated (what is this?). This address can be used by the programmer to access the allocated memory. When done using memory, it must be explicitly freed.
  • 9. Explicitly allocating memory in C++: The ‘new’ Operator • Used to dynamically allocate memory • Can be used to allocate a single variable/object or an array of variables/objects • The new operator returns pointer to the type allocated • Before the assignment, the pointer may or may not point to a legitimate memory • After the assignment, the pointer points to a legitimate memory.
  • 10.
  • 11. Explicitly freeing memory in C++: The ‘delete’ Operator • Used to free memory allocated with new operator • The delete operator should be called on a pointer to dynamically allocated memory when it is no longer needed • Can delete a single variable/object or an array delete PointerName; delete [] ArrayName; • After delete is called on a memory region, that region should no longer be accessed by the program • Convention is to set pointer to deleted memory to NULL Any new must have a corresponding delete --- if not, the program has memory leak. New and delete may not be in the same routine.
  • 12.
  • 13. Example • int main() • { • // Below variables are allocated memory • // dynamically. • int *ptr1 = new int; • int *ptr2 = new int[10]; • • // Dynamically allocated memory is • // deallocated • delete ptr1; • delete [] ptr2; • }
  • 14. The Heap • Large area of memory controlled by the runtime system that is used to grant dynamic memory requests. • It is possible to allocate memory and “lose” the pointer to that region without freeing it. This is called a memory leak. • A memory leak can cause the heap to become full • If an attempt is made to allocate memory from the heap and there is not enough, an exception is generated (error)
  • 15. Why use dynamic memory allocation? • Allows data (especially arrays) to take on variable sizes (e.g. ask the user how many numbers to store, then generate an array of integers exactly that size). • Allows locally created variables to live past end of routine. • Allows us to create many structures used in Data Structures and Algorithms
  • 16. The . and -> operators • The dot operator is used to access an object’s members ▫ M1.Simplify(); ▫ M1.num = 5; • But how do we access an objects members if we only have a pointer to the object? • If we have M1_ptr = &M1, Perhaps we would use (*(M1_ptr)).Simplify() • A shorthand for this is the arrow operator • M1_ptr->Simplify() is equivalent to(*(M1_ptr)).Simplify()
  • 18. Linked Lists • Linked List is a very commonly used linear data structure which consists of group of nodes in a sequence. • Each node holds its own data and the address of the next node hence forming a chain like structure. • Linked Lists are used to create trees and graphs.
  • 20. Types of Linked Lists There are 3 different implementations of Linked List available, they are: 1. Singly Linked List 2. Doubly Linked List 3. Circular Linked List
  • 21. Singly Linked List • Singly linked lists contain nodes which have a data part as well as an address part i.e. next, which points to the next node in the sequence of nodes. • The operations we can perform on singly linked lists are insertion, deletion and traversal.
  • 22.
  • 23. Doubly Linked List • In a doubly linked list, each node contains a data part and two addresses, one for the previous node and one for the next node.
  • 24.
  • 25. Circular Linked List • In circular linked list the last node of the list holds the address of the first node hence forming a circular chain.
  • 26.
  • 27. Advantages of Linked Lists • They are a dynamic in nature which allocates the memory when required. • Insertion and deletion operations can be easily implemented. • Linked List reduces the access time.
  • 28. Disadvantages of Linked Lists • The memory is wasted as pointers require extra memory for storage. • No element can be accessed randomly; it has to access each node sequentially. • Reverse Traversing is difficult in linked list. • Not cache friendly. Since array elements are contiguous locations, there is locality of reference which is not there in case of linked lists.
  • 29. Applications of Linked Lists • Linked lists are used to implement stacks, queues, graphs, etc. Linked lists let you insert elements at the beginning and end of the list. In Linked Lists we don't need to know the size in advance
  • 30. Array vs Linked List • Both Linked List and Array are used to store linear data of similar type, but an array consumes contiguous memory locations allocated at compile time, i.e. at the time of declaration of array, while for a linked list, memory is assigned as and when data is added to it, which means at runtime.
  • 31. On the left, we have Array and on the right, we have Linked List.
  • 32. Summary • Dynamic Memory Allocation ▫ New Operator ▫ Delete Operator ▫ Heap ▫ dot . and -> operators • Introduction to Linked List ▫ Types ▫ Advantages ▫ Disadvantages ▫ Applications ▫ Difference between Array and Linked List
  • 33. References • https://www.geeksforgeeks.org/what-is-dynamic- memory-allocation/ • https://www.geeksforgeeks.org/new-and-delete- operators-in-cpp-for-dynamic-memory/ • https://www.youtube.com/watch?v=texoDnnzWao • https://www.studytonight.com/data- structures/introduction-to-linked-list • https://www.geeksforgeeks.org/linked-list-set-1- introduction/