CS 536 Class Notes for April 19, 1999 by S. Nicole Little Topics for Today - Heap Allocation - Heal deallocation A heap is a big block of space _ _____________________ | | | | | heap | |_|_____________________| ^ | size of the heap _ _____ _ _____ _ _____ _____ |1| |2| |3| | | |0| |0| |0| | | |0|_____|0|_____|0|_____|_____| \ | / \ \ | / \ headers for free space allocated space In order to deallocate the 200 bytes - keep a free space list (FSL - linked list) - simply place the oject (200) into the free space list - ordered by adding (unordered list) Ways to allocate space when a free space list is being implemented 1) First fit - looks for the first place where he allocation fits - leaves lots of little gaps that may become too small to be practical 2) Best Fit - looks for the best fit - as close to fit as possible - takes time, must look thru the whole list 3) Circular Fit - eliminates front end clutter, spreads out allocation Note - adjacent free space can be merged USER CONTROLLED DEALLOCATION Two pointers - free(ptr) assigned to the printer after dispose - dispose(ptr) assigned to the object to be disposed Problem - logging space, what has is still needed and what is not - example p = new int; q = p; delete p; // q space is also deallocated *q = 123 // What happens here? No way to Predict Therefore we move to system control of deallocation SYSTEM CONTROLLED DEALLOCATION - very popular - reliable How does it work? -system tracks objects and decides when they are garbage + tracks creation and deletion of pointers + free memory - objects that cannot be reached Options 1) Refernece Counting a) _ _ ________ keep track of how many pointers are | | | | pointing to an object | | | heap | |_|_|________| / \ count header(size) b) Code that amnipulates pointers will also adjust counter (i.e. null assignment subtract count) c) If you go out of scope it is essentially deleted d) drawbacks - more expensive operations - makes you pay incrementally 2) Mark and Sweep a) two passes b) pay almost nothing until heap is almost running out c) idea - look at heap state(when) almost out of memory - mark the active object of the heap + global pointers + locals + heap objects - sweep + check if marked + if not marked, add to free space d) how do we decide what to mark? - look for big numbers that look like heap pointers - may mark things that are not active but all active things will be marked