SlideShare a Scribd company logo
1 of 16
Memory Handling
&
Garbage Collection in Python
Prepared by:
Ms. Pooja Mehta
ITSNS Branch,
GTU-CDAC-BISAG ME Program,
Gandhinagar
1
Memory Management
3 March 2016By: Pooja Mehta
2
 The process of binding values to memory
locations
 Whether done automatically (as in
Python), or partially by the programmer
(as in C/C++), dynamic memory
management is an important part of
programming language design.
Three Categories of Memory
(for Data Storage)
3 March 2016By: Pooja Mehta
3
 Static: storage requirements are known
prior to run time; lifetime is the entire
program execution
 Run-time stack: memory associated with
active functions
Structured as stack frames
 Heap: dynamically allocated storage; the
least organized and most dynamic storage
area
Cont..
3 March 2016By: Pooja Mehta
4
Cont..
3 March 2016By: Pooja Mehta
5
Memory Leaks and Garbage
Collection
3 March 2016By: Pooja Mehta
6
 Three types of storage
 Static
 Stack
 Heap
 Problems with heap storage:
 Memory leaks (garbage): failure to free storage when
pointers (references) are reassigned
 Dangling pointers: when storage is freed, but
references to the storage still exist.
Garbage
3 March 2016By: Pooja Mehta
7
 Any block of heap memory that cannot be
accessed by the program; i.e., there is no
stack pointer to the block; but which the
runtime system thinks is in use.
 Garbage is created in several ways:
 A function ends without returning the space
allocated to a local array or other dynamic
variable.
 A node is deleted from a linked data structure, but
isn’t freed
Garbage Collection
3 March 2016By: Pooja Mehta
8
 All inaccessible blocks of storage are identified
and returned to the free list.
 The heap may also be compacted at this time:
allocated space is compressed into one end of
the heap, leaving all free space in a large
block at the other end.
Implementing Automated
Garbage Collection
3 March 2016By: Pooja Mehta
9
 If programmers were perfect, garbage
collection wouldn’t be needed.
 There are three major approaches to
automating the process:
 Reference counting
 Mark-sweep
 Copy collection
Reference Counting
10
 Prior to Python version 2.0, the Python
interpreter only used reference counting for
memory management.
 Reference counting works by counting the
number of times an object is referenced by
other objects in the system.
 When references to an object are removed,
the reference count for an object is
decremented.
 When the reference count becomes zero the
object is de allocated.
3 March 2016By: Pooja Mehta
Mark and Sweep
3 March 2016By: Pooja Mehta
11
 Reference counting tries to find unreachable
objects by finding objects with no incoming
references.
 Imprecise because we forget which references
those are.
Cont..
3 March 2016By: Pooja Mehta
12
 The root set is the set of memory locations in
the program that are known to be reachable.
 Any objects reachable from the root set are
reachable.
 Any objects not reachable from the root set are
not reachable.
Cont..
3 March 2016By: Pooja Mehta
13
Marking phase: Find reachable objects.
 Add the root set to a worklist.
 While the worklist isn't empty:
 Remove an object from the worklist.
 If it is not marked, mark it and add to the worklist all
objects reachable from that object.
Sweeping phase: Reclaim free memory.
 For each allocated object:
 If that object isn't marked, reclaim its memory.
 If the object is marked, unmark it (so on the next
mark-and sweep iteration we have to mark it again).
Copy Collection
3 March 2016By: Pooja Mehta
14
 Divide heap into two “semispaces”.
 Allocate from one space (fromspace) till full.
 Copy live data into other space (tospace).
 Switch roles of the spaces.
 Requires fixing pointers to moved data
(forwarding).
 Eliminates fragmentation.
 DFS improves locality, while BFS does not
require any extra storage.
References
15
 https://docs.python.org/2/c-api/memory.html
 http://foobarnbaz.com/2012/07/08/understanding-
python-variables/
 https://www.digi.com/wiki/developer/index.php/Pyt
hon_Garbage_Collection
3 March 2016By: Pooja Mehta
16
Thank
you...!

More Related Content

Viewers also liked

GALNT11 as a new molecular marker in chronic lymphocytic leukemia
GALNT11 as a new molecular marker in chronic lymphocytic leukemiaGALNT11 as a new molecular marker in chronic lymphocytic leukemia
GALNT11 as a new molecular marker in chronic lymphocytic leukemiaDiana Agudelo
 
Kossuth Palo Alto Economic Development Crop Jan-June Newsletter
Kossuth Palo Alto Economic Development Crop Jan-June NewsletterKossuth Palo Alto Economic Development Crop Jan-June Newsletter
Kossuth Palo Alto Economic Development Crop Jan-June NewsletterMid Iowa Growth Partnership
 
BACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSE
BACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSEBACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSE
BACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSEDiana Agudelo
 
GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"
GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"
GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"gamificationworldcongress
 
GWC14: Carlos Guardiola - "Who gamifies the gamificators?
GWC14: Carlos Guardiola - "Who gamifies the gamificators?GWC14: Carlos Guardiola - "Who gamifies the gamificators?
GWC14: Carlos Guardiola - "Who gamifies the gamificators?gamificationworldcongress
 
Presentasjon om biler
Presentasjon om bilerPresentasjon om biler
Presentasjon om bilerAbdelhay1961
 
GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"
GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"
GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"gamificationworldcongress
 
GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"
GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"
GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"gamificationworldcongress
 
Elao integral presentation
Elao integral presentationElao integral presentation
Elao integral presentationElenaSoto75
 
2011 Fort Dodge & Webster County Iowa Laborshed Summary
2011 Fort Dodge & Webster County Iowa Laborshed Summary2011 Fort Dodge & Webster County Iowa Laborshed Summary
2011 Fort Dodge & Webster County Iowa Laborshed SummaryMid Iowa Growth Partnership
 
Presentasjon om biler2
Presentasjon om biler2Presentasjon om biler2
Presentasjon om biler2Abdelhay1961
 

Viewers also liked (19)

No-no-no approach
No-no-no approachNo-no-no approach
No-no-no approach
 
GALNT11 as a new molecular marker in chronic lymphocytic leukemia
GALNT11 as a new molecular marker in chronic lymphocytic leukemiaGALNT11 as a new molecular marker in chronic lymphocytic leukemia
GALNT11 as a new molecular marker in chronic lymphocytic leukemia
 
Kossuth Palo Alto Economic Development Crop Jan-June Newsletter
Kossuth Palo Alto Economic Development Crop Jan-June NewsletterKossuth Palo Alto Economic Development Crop Jan-June Newsletter
Kossuth Palo Alto Economic Development Crop Jan-June Newsletter
 
MUN U.K.
MUN U.K.MUN U.K.
MUN U.K.
 
BACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSE
BACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSEBACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSE
BACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSE
 
GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"
GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"
GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"
 
GWC14: Carlos Guardiola - "Who gamifies the gamificators?
GWC14: Carlos Guardiola - "Who gamifies the gamificators?GWC14: Carlos Guardiola - "Who gamifies the gamificators?
GWC14: Carlos Guardiola - "Who gamifies the gamificators?
 
Presentasjon om biler
Presentasjon om bilerPresentasjon om biler
Presentasjon om biler
 
GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"
GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"
GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"
 
Function points and elements
Function points and elementsFunction points and elements
Function points and elements
 
GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"
GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"
GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"
 
Days remembered
Days rememberedDays remembered
Days remembered
 
Katharina reiss
Katharina reissKatharina reiss
Katharina reiss
 
Fgd medan
Fgd medanFgd medan
Fgd medan
 
19 Feb 2011 ZGM
19 Feb 2011 ZGM19 Feb 2011 ZGM
19 Feb 2011 ZGM
 
Elao integral presentation
Elao integral presentationElao integral presentation
Elao integral presentation
 
Tugas agama
Tugas agamaTugas agama
Tugas agama
 
2011 Fort Dodge & Webster County Iowa Laborshed Summary
2011 Fort Dodge & Webster County Iowa Laborshed Summary2011 Fort Dodge & Webster County Iowa Laborshed Summary
2011 Fort Dodge & Webster County Iowa Laborshed Summary
 
Presentasjon om biler2
Presentasjon om biler2Presentasjon om biler2
Presentasjon om biler2
 

More from POOJA MEHTA

Data Validation for Business Continuity Planning
Data Validation for Business Continuity PlanningData Validation for Business Continuity Planning
Data Validation for Business Continuity PlanningPOOJA MEHTA
 
Otp authentication scheme based on ECC
Otp authentication scheme based on ECCOtp authentication scheme based on ECC
Otp authentication scheme based on ECCPOOJA MEHTA
 
Fault tolerance in Big Data
Fault tolerance in Big DataFault tolerance in Big Data
Fault tolerance in Big DataPOOJA MEHTA
 
Computer organization and architecture
Computer organization and architectureComputer organization and architecture
Computer organization and architecturePOOJA MEHTA
 
The optimization and implementation of iptables rules set
The optimization and implementation of iptables rules setThe optimization and implementation of iptables rules set
The optimization and implementation of iptables rules setPOOJA MEHTA
 
Deadlock Detection
Deadlock DetectionDeadlock Detection
Deadlock DetectionPOOJA MEHTA
 
Network Data Representation
Network Data RepresentationNetwork Data Representation
Network Data RepresentationPOOJA MEHTA
 

More from POOJA MEHTA (7)

Data Validation for Business Continuity Planning
Data Validation for Business Continuity PlanningData Validation for Business Continuity Planning
Data Validation for Business Continuity Planning
 
Otp authentication scheme based on ECC
Otp authentication scheme based on ECCOtp authentication scheme based on ECC
Otp authentication scheme based on ECC
 
Fault tolerance in Big Data
Fault tolerance in Big DataFault tolerance in Big Data
Fault tolerance in Big Data
 
Computer organization and architecture
Computer organization and architectureComputer organization and architecture
Computer organization and architecture
 
The optimization and implementation of iptables rules set
The optimization and implementation of iptables rules setThe optimization and implementation of iptables rules set
The optimization and implementation of iptables rules set
 
Deadlock Detection
Deadlock DetectionDeadlock Detection
Deadlock Detection
 
Network Data Representation
Network Data RepresentationNetwork Data Representation
Network Data Representation
 

Recently uploaded

Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 

Recently uploaded (20)

Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 

Memory Handling and Garbage Collection in Python

  • 1. Memory Handling & Garbage Collection in Python Prepared by: Ms. Pooja Mehta ITSNS Branch, GTU-CDAC-BISAG ME Program, Gandhinagar 1
  • 2. Memory Management 3 March 2016By: Pooja Mehta 2  The process of binding values to memory locations  Whether done automatically (as in Python), or partially by the programmer (as in C/C++), dynamic memory management is an important part of programming language design.
  • 3. Three Categories of Memory (for Data Storage) 3 March 2016By: Pooja Mehta 3  Static: storage requirements are known prior to run time; lifetime is the entire program execution  Run-time stack: memory associated with active functions Structured as stack frames  Heap: dynamically allocated storage; the least organized and most dynamic storage area
  • 4. Cont.. 3 March 2016By: Pooja Mehta 4
  • 5. Cont.. 3 March 2016By: Pooja Mehta 5
  • 6. Memory Leaks and Garbage Collection 3 March 2016By: Pooja Mehta 6  Three types of storage  Static  Stack  Heap  Problems with heap storage:  Memory leaks (garbage): failure to free storage when pointers (references) are reassigned  Dangling pointers: when storage is freed, but references to the storage still exist.
  • 7. Garbage 3 March 2016By: Pooja Mehta 7  Any block of heap memory that cannot be accessed by the program; i.e., there is no stack pointer to the block; but which the runtime system thinks is in use.  Garbage is created in several ways:  A function ends without returning the space allocated to a local array or other dynamic variable.  A node is deleted from a linked data structure, but isn’t freed
  • 8. Garbage Collection 3 March 2016By: Pooja Mehta 8  All inaccessible blocks of storage are identified and returned to the free list.  The heap may also be compacted at this time: allocated space is compressed into one end of the heap, leaving all free space in a large block at the other end.
  • 9. Implementing Automated Garbage Collection 3 March 2016By: Pooja Mehta 9  If programmers were perfect, garbage collection wouldn’t be needed.  There are three major approaches to automating the process:  Reference counting  Mark-sweep  Copy collection
  • 10. Reference Counting 10  Prior to Python version 2.0, the Python interpreter only used reference counting for memory management.  Reference counting works by counting the number of times an object is referenced by other objects in the system.  When references to an object are removed, the reference count for an object is decremented.  When the reference count becomes zero the object is de allocated. 3 March 2016By: Pooja Mehta
  • 11. Mark and Sweep 3 March 2016By: Pooja Mehta 11  Reference counting tries to find unreachable objects by finding objects with no incoming references.  Imprecise because we forget which references those are.
  • 12. Cont.. 3 March 2016By: Pooja Mehta 12  The root set is the set of memory locations in the program that are known to be reachable.  Any objects reachable from the root set are reachable.  Any objects not reachable from the root set are not reachable.
  • 13. Cont.. 3 March 2016By: Pooja Mehta 13 Marking phase: Find reachable objects.  Add the root set to a worklist.  While the worklist isn't empty:  Remove an object from the worklist.  If it is not marked, mark it and add to the worklist all objects reachable from that object. Sweeping phase: Reclaim free memory.  For each allocated object:  If that object isn't marked, reclaim its memory.  If the object is marked, unmark it (so on the next mark-and sweep iteration we have to mark it again).
  • 14. Copy Collection 3 March 2016By: Pooja Mehta 14  Divide heap into two “semispaces”.  Allocate from one space (fromspace) till full.  Copy live data into other space (tospace).  Switch roles of the spaces.  Requires fixing pointers to moved data (forwarding).  Eliminates fragmentation.  DFS improves locality, while BFS does not require any extra storage.
  • 15. References 15  https://docs.python.org/2/c-api/memory.html  http://foobarnbaz.com/2012/07/08/understanding- python-variables/  https://www.digi.com/wiki/developer/index.php/Pyt hon_Garbage_Collection 3 March 2016By: Pooja Mehta

Editor's Notes

  1. The user does not have to preallocate or deallocate memory by hand as one has to when using dynamic memory allocation in languages such as C or C++.
  2. The easiest way to create a reference cycle is to create an object which refers to itself as in the example below: def make_cycle(): l = [ ] l.append(l) make_cycle() Reference counting is extremely efficient but it does have some caveats. One such caveat is that it cannot handle reference cycles. A reference cycle is when there is no way to reach an object but its reference count is still greater than zero.
  3. Problems Memory Fragmentation Work proportional to size of heap Potential lack of locality of reference for newly allocated objects (fragmentation) Solution Compaction Contiguous live objects, contiguous free space
  4. Automatic Garbage Collection of Cycles Because reference cycles are take computational work to discover, garbage collection must be a scheduled activity. Python schedules garbage collection based upon a threshold of object allocations and object deallocations. When the number of allocations minus the number of deallocations are greater than the threshold number, the garbage collector is run. One can inspect the threshold for new objects (objects in Python known as generation 0 objects) by loading the gc module and asking for garbage collection thresholds. Because make_cycle() creates an object l which refers to itself, the object l will not automatically be freed when the function returns. This will cause the memory that l is using to be held onto until the Python garbage collector is invoked