3. Motivation
Managing memory manually is hard.
Who owns the memory?
Should I free these resources?
What happens with double frees?
Francisco Fernandez Castano (@fcofdezc) Python GC October 21, 2014 3 / 37
4. Dangling pointers
int * func ( void )
{
int num = 1234;
/* ... */
return &num ;
}
Francisco Fernandez Castano (@fcofdezc) Python GC October 21, 2014 4 / 37
5. Ownership
int * func ( void )
{
int *num = malloc (10 * sizeof (int ));;
/* ... */
return num ;
}
Francisco Fernandez Castano (@fcofdezc) Python GC October 21, 2014 5 / 37
7. Basic concepts
Heap
A data structure in which objects may be allocated or deallocated in any
order.
Francisco Fernandez Castano (@fcofdezc) Python GC October 21, 2014 7 / 37
8. Basic concepts
Heap
A data structure in which objects may be allocated or deallocated in any
order.
Mutator
The part of a running program which executes application code.
Francisco Fernandez Castano (@fcofdezc) Python GC October 21, 2014 8 / 37
9. Basic concepts
Heap
A data structure in which objects may be allocated or deallocated in any
order.
Mutator
The part of a running program which executes application code.
Collector
The part of a running program responsible of garbage collection.
Francisco Fernandez Castano (@fcofdezc) Python GC October 21, 2014 9 / 37
11. nition
Garbage collection is automatic memory management. While the
mutator runs , it routinely allocates memory from the heap. If more
memory than available is needed, the collector reclaims unused memory
and returns it to the heap.
Francisco Fernandez Castano (@fcofdezc) Python GC October 21, 2014 10 / 37
12. CPython GC
CPython implementation has garbage collection.
CPython GC algorithm is Reference counting with cycle detector
It also has a generational GC.
Francisco Fernandez Castano (@fcofdezc) Python GC October 21, 2014 11 / 37
13. Young objects
[ elem * 2 for elem in elements ]
balance = (a / b / c) * 4
'asdadsasd - xxx '. replace ('x', 'y'). replace ('a', 'b')
foo.bar ()
Francisco Fernandez Castano (@fcofdezc) Python GC October 21, 2014 12 / 37
30. Reference counting
Pros: Is incremental, as it works, it frees memory.
Cons: Detecting Cycles could be hard.
Cons: Size overhead on objects.
Francisco Fernandez Castano (@fcofdezc) Python GC October 21, 2014 29 / 37
32. Mark and Sweep Algorithm
Francisco Fernandez Castano (@fcofdezc) Python GC October 21, 2014 31 / 37
33. Mark and Sweep Algorithm
Francisco Fernandez Castano (@fcofdezc) Python GC October 21, 2014 32 / 37
34. Mark and Sweep Algorithm
Francisco Fernandez Castano (@fcofdezc) Python GC October 21, 2014 33 / 37
35. Mark and Sweep Algorithm
Francisco Fernandez Castano (@fcofdezc) Python GC October 21, 2014 34 / 37
36. Mark and sweep
Pros: Can collect cycles.
Cons: Basic implementation stops the world
Francisco Fernandez Castano (@fcofdezc) Python GC October 21, 2014 35 / 37