Advanced Programming
|
|
- Quentin Cook
- 5 years ago
- Views:
Transcription
1 Advanced Programming Memory Management The Heap Dr. Miri (Kopel) Ben-Nissan Bar-Ilan University
2 The Traditional Heap Manager The standard C library routines for allocating and freeing memory are malloc() and free(). C++ uses the new and delete operators. void* malloc ( size_t size ); void free ( void *memblock ); Void* operator new (size_t); void operator delete (void*); Void* operator new[](size_t); void operator delete[](void*); 2
3 The Traditional Heap Manager (Cont ) Main problem with those interfaces: they assumes the programmer never makes a mistake in calling the memory management functions. #include <stdlib.h> int main(void) { void *pmem=malloc(100); 3 free(pmem); free(pmem); return 0; } <- behavior undefined!
4 The Traditional Heap Manager (Cont ) Besides the interface, there is also general problems with dynamic memory allocations: Allocation and de-allocation are non-deterministic with respect to time. De-allocation: Explicit by the programmer can cause memory leaks if not handled correctly. Implicit by garbage collector, nondeterministic. Fragmentation problem. 4
5 malloc void *malloc(long numbytes): This allocates numbytes of memory and returns a pointer to the first byte. Returns NULL if failed. Guaranties well fragmentation. void free(void *firstbyte): Given a pointer that has been returned by a previous malloc, this gives the space that was allocated back to the process's "free space." 5
6 malloc (cont ) You can imagine the heap as a vector of bytes (characters), starting at address managed_memory_start, and last_valid_address as a pointer to the first available byte in the heap. int has_initialized = 0; void *managed_memory_start; //start of heap void *last_valid_address; //end of heap void *last_allocated= managed_memory_start; //no allocations yet. 6
7 7 malloc (cont )
8 malloc (cont ) A trivial implementation of malloc in C is: void* malloc ( int size ) { void* loc = last_allocated; }; last_allocated += size; return loc; 8
9 malloc (cont ) If you always create dynamic structures but never delete them, you will eventually run out of heap space. In that case, malloc will request the operating system for more heap. This is very expensive, because it may require to move the stack data to higher memory locations. 9
10 malloc (cont ) Alternatively, you can recycle the dynamically allocated data that you don't use. This is done using free in C or delete in C++. How we will know how many bytes to move the pointer back? What if it is in the middle of the heap? 10
11 malloc (cont ) We will add an header to each allocated block in the heap: struct mem_control_block { int is_available; int size; }; 11
12 malloc (cont ) As said previously, the heap is a continues (in terms of virtual address) space of memory with three bounds: Starting point. Maximum limit. End point (break). The break marks the end of the mapped memory spaces, that is, the part of the virtual address space that has correspondence into real memory. 12
13 malloc (cont ) In the Unix operating system, we find the following two system calls that enables us to control the break border: brk places the break at the given address addr and returns 0 if successful, -1 otherwise. sbrk moves the break by the given increment (in bytes). Depending on system implementation, it returns the previous or the new break address. On failure, it returns (void*)-1. On some systems, sbrk accepts negative values (in order to free some mapped memory). 13
14 when increment is null (i.e. sbrk(0)), the returned value is the actual break address. sbrk is thus used to retrieve the beginning of the heap which is the initial position of the break. Accessing addresses above the break should trigger a bus error. The remaining space between the break and the maximum limit of the heap is not associated to physical memory by the virtual memory manager of the system. 14
15 malloc (cont ) #include <unistd.h> /* Include the sbrk function */ int has_initialized = 0; void *managed_memory_start; void *last_valid_address; void malloc_init() { /* grab the last valid address from the OS */ last_valid_address = sbrk(0); /* we assume that managed memory size at the beginning * is empty, so just set the beginning to be last_valid_address */ managed_memory_start = last_valid_address; } 15 has_initialized = 1;
16 malloc (cont ) struct mem_control_block { int is_available; int size; }; void free(void *firstbyte) { struct mem_control_block *mcb; mcb = firstbyte - sizeof(struct mem_control_block); mcb->is_available = 1; } 16 return;
17 void *malloc(long numbytes) { /* Holds where we are looking in memory */ void *current_location; /* This is the same as current_location, but cast to a memory_control_block */ struct mem_control_block *current_location_mcb; void *memory_location; malloc (cont ) 17 if(! has_initialized) { malloc_init(); }
18 THE HEAP malloc (cont ) numbytes = numbytes + sizeof(struct mem_control_block); /* Set memory_location to 0 until we find a suitable location */ memory_location = 0; /* Begin searching at the start of managed memory */ current_location = managed_memory_start; managed_memory_start current_location header numbytes last_valid_address 18
19 19 malloc (cont ) /* Keep going until we have searched all allocated space */ while(current_location!= last_valid_address) { current_location_mcb = (struct mem_control_block *)current_location; if(current_location_mcb->is_available){ if(current_location_mcb->size >= numbytes){ current_location_mcb->is_available = 0; memory_location = current_location; break; } } /* If we made it here, it's because the current memory * block not suitable, move to the next one */ current_location = current_location + current_location_mcb->size; }
20 malloc (cont ) /* If we still don't have a valid location, we'll have to ask the operating * system for more memory */ if(! memory_location) { /* Move the program break numbytes further */ if (sbrk(numbytes) == (void*)(-1) return 0; /*unable to resize heap size.*/ /* The new memory will be where the last valid address left off */ memory_location = last_valid_address; /* We'll move the last valid address forward numbytes */ last_valid_address = last_valid_address + numbytes; } 20 /* We need to initialize the mem_control_block */ current_location_mcb = (struct mem_control_block *)memory_location; current_location_mcb->is_available = 0; current_location_mcb->size = numbytes;
21 malloc (cont ) /* Move the pointer past the mem_control_block */ memory_location = memory_location + sizeof(struct mem_control_block); } /* Return the pointer */ return memory_location; Taken from: 21
22 malloc (cont ) Exercise Write an aligned malloc & free function, which takes two parameters: The number of bytes to allocate. The aligned byte (which is always power of 2). Example: align_malloc (1000,128); will allocate the memory and return a memory address which is a multiplication of 128. aligned_free(); will free memory allocated by align_malloc. 22
23 Allocation Policies Allocation Policy = The concrete policy used by an allocator (memory manager) for choosing a free block to satisfy an allocation request. Two methods: Fixed size blocks. Variable size blocks. Most popular policies (for both methods): First Fit Best Fit Next Fit 23
24 Notice: malloc allocates pages (or chunks ) of fixed size. Than this chunk is split: part of it goes to the user, and the rest goes to the free-blocks list. 24
25 Allocation Policies (Cont ) Best-fit: choose smallest hole that fits creates small holes! First-fit: choose first hole from beginning that fits generally superior Next-fit: variation: first hole from last placement that fits. (also worst fit) 25
26 Allocation Policies (Cont ) First fit simply searches the free list from the beginning, and uses the first free block large enough to satisfy the request. If the block is larger than necessary, it is either used as is (internal fragmentation) or split and the remainder is put on the free list. Easy to implement Memory overhead is small. Internal fragmentation. Lots of small blocks at the beginning 26
27 Allocation Policies (Cont ) Best Fit always allocates from the smallest suitable free block. In theory, best fit may exhibit bad fragmentation, but in practice this is not commonly observed. Minimizes the amount of wasted space Sequential best-fit is inefficient 27
28 Allocation Policies (Cont ) Next Fit is a variant of the first fit allocation mechanism that uses a roving pointer on a circular free block chain. Each allocation begins looking where the previous one finished. No accumulation of small blocks, which would have to be examined on every allocation. Generally increases fragmentation, like first-fit. Tendency to spread related objects out in memory. Gives quite poor locality for the allocator (as the roving pointer rotates around memory, the free blocks touched are those least-recently used). 28
29 Allocation Policies (Cont ) All algorithms can be improved by keeping the information about the free blocks in the heap. There are many techniques for that, like: Free-page bitmap. Free list. And many more Some of the techniques allocates fixed-size blocks and other a variable-sized blocks. 29
30 Allocation Policies (Cont ) Free-page bitmap. Every bit in the bitmap represents one 4096 byte (4KB) block in the heap. If the bit is 0, the block has been allocated. If the bit is 1, then it is free. Assume a 4MB heap. Each allocated block is 4KB. allocation: O(N) free: O(1) The free page bitmap is 1024 bits wide: 4MB = 4096KB => 4096KB/4096B =
31 Allocation Policies (Cont ) Free list is a linked list of freeblock structures. struct freeblock { struct freeblock *next; char garbage[4092]; }; 31 Internal fragmentation! In the data portion of the processes, we store a pointer which points to the first freeblock structure.
32 Allocation Policies (Cont ) Variable Size Allocations allows the allocation of memory of variable sizes. Instead of having several smaller blocks to allocate, we start with one big block of memory and split it as necessary to make smaller blocks. struct freeblock { struct freeblock *next; size_t size; }; 32
33 Allocation Policies (Cont ) Segregated free lists uses a set of lists of free blocks. Each list holds blocks of a given size A freed block is pushed onto the relevant list When a block is needed, the relevant list is used 33
34 Memory Allocation in C++ Even though malloc and free are available in C++, their use is not recommended. It is always preferred to use new and delete, especially when working with objects. new and delete point to the correct memory type (they are type safe), so casts are not necessary. new invokes the constructor, allowing the initialization of objects, and delete invokes the destructor. new figures out the size it needs to allocate, so the programmer doesn't have to specify it. new throws an exception of type std::bad_alloc when it fails, instead of only returning a NULL pointer like malloc. 34
35 new and delete void* operator new(size_t); void operator delete(void*); void* operator new[](size_t); void operator delete[](void*); 35
36 The new & delete operators Do I need to check for NULL after p = new Fred()? 36
37 The new & delete operator (Cont ) failure Attempt to allocate memory success no Handler installed? yes Return the address Throw bad_alloc Call the handler function retry 37
38 The new & delete operators (Cont ) Do I need to check for NULL after p = new Fred()? Do NOT check for NULL when allocating memory with new, since new will never return NULL! The ptr will retain its previous value. Malloc can fail. When you call malloc, or when you get a pointer back from a function that calls malloc, you should check to ensure that the pointer you got back wasn't NULL. 38
39 The new & delete operators (Cont ) Until the early 1990s, operator new behaved very much like standard C's malloc(), as far as allocation failures were concerned. When it failed to allocated a memory block of the requested size, it would return a NULL pointer. This behavior was changed in the early 1990s. Instead of returning a NULL pointer, new throws an exception of type std::bad_alloc to indicate a failure. Testing the return value is utterly wrong. 39
40 The new & delete operators (Cont ) p = new CMyClass; if (!p){ //not to be used under ISO //compliant compilers cout<<"allocation failure! ; exit(1); } The if condition is never evaluated in the event of an allocation failure, because the exception thrown by new has already transferred control to a matching catch() clause, if one exists. If no matching catch() is found, C++ automatically calls function terminate() that terminates the program unconditionally. 40
41 The new & delete operators (Cont ) try { p = new DerivedWind; } catch (std::bad_alloc &ba) { cout<<"allocation failure! ; //...additional cleanup } Embedded systems don't always support exceptions. In such environments, nothrow new can be rather useful. 41
42 The new & delete operator (Cont ) Before operator new throws an exception, it calls a client-specified error-handling function, called a newhandler. To specify the out-of-memory-handling function, clients call set_new_handler, a standard library function declared in <new>: namespace std { typedef void(*new_handler_ptr)(); //ptr to function new_handler set_new_handler(new_handler_ptr p) throw(); } 42
43 The new & delete operator (Cont ) Example: void OutOfMem() { std::cerr<< Failed to allocate memory\n ; std::abort(); } int main() { std::set_new_handler(outofmem); int* pbigdataarray = new int[ l]; // } 43
44 The new & delete operator (Cont ) A well designed new-handler function must do one of the following: 44 Make more memory available. Install a different new-handler. De-install the new-handler, by passing NULL to set_new_handler. Like this the new operator will throw an exception. Throw an exception. No return (abort or exit).
45 The new & delete operator (Cont ) Further reading at home: Handling memory failures in different ways, depending on the class of the object being allocated. (Effective C++, pages ). 45
46 Overloading new & delete When you overload operator new and operator delete, you re changing only the way raw storage is allocated. The compiler will simply call your new instead of the default version to allocate storage, then call the constructor for that storage. So, although the compiler allocates storage and calls the constructor when it sees new, all you can change when you overload new is the storage allocation portion. (delete has a similar limitation). 46
47 Overloading new & delete (Cont ) When you overload operator new, you also replace the behavior when it runs out of memory, so you must decide what to do in your operator new. (return zero, write a loop to call the new-handler and retry allocation, or (typically) throw a bad_alloc exception). 47
48 Overloading global new & delete When the global versions of new and delete are unsatisfactory for the whole system. If you overload the global versions, you make the defaults completely inaccessible you can t even call them from inside your redefinitions. 48
49 Overloading global new & delete (Cont ) The overloaded new must take an argument of size_t (the Standard C standard type for sizes). You must return a pointer either to an object of that size (or bigger, if you have some reason to do so), or to zero if you can t find the memory (in which case the constructor is not called!). However, if you can t find the memory, you should probably do something more drastic than just returning zero, like calling the new-handler or throwing an exception, to signal that there s a problem. The return value of operator new is a void*, not a pointer to any particular type. 49
50 Overloading global new & delete (Cont ) The operator delete takes a void* to memory that was allocated by operator new. It s a void* because you get that pointer after the destructor is called, which removes the object-ness from the piece of storage. The return type is void. 50
51 Overloading global new & delete (Cont ) #include <cstdio> #include <cstdlib> using namespace std; void* operator new(size_t sz) { printf("operator new: %d Bytes\n", sz); void* m = malloc(sz); if(!m) puts("out of memory"); return m; } void operator delete(void* m) { puts("operator delete"); free(m); } 51
52 Overloading global new & delete (Cont ) class S { int i[100]; public: S() { puts("s::s()"); } ~S() { puts("s::~s()"); } }; 52
53 Overloading global new & delete (Cont ) int main() { puts("creating & destroying an int"); int* p = new int(47); delete p; puts("creating & destroying an s"); S* s = new S; delete s; puts("creating & destroying S[3]"); S* sa = new S[3]; delete []sa; } 53
54 Overloading new & delete for arrays (Cont ) After p = new Fred[n], how does the compiler know there are n objects to be destructed during delete[ ] p? The run-time system stores the number of objects, n, somewhere where it can be retrieved if you only know the pointer, p. There are two popular techniques that do this. Both these techniques are in use by commercial-grade compilers, both have tradeoffs, and neither is perfect. 54
55 Overloading new & delete for arrays (Cont ) These techniques are: Over-allocate the array and put n just to the left of the first Fred object. Use an associative array with p as the key and n as the value. 55
56 Overloading new & delete for arrays (Cont ) Using "over-allocation" (header) to remember the number of elements in an allocated array. Each block, allocated or freed, contains a header. Usually the heap simply consists of two lists of cells; one is the list of allocated cells and the other the list of free cells. 56
57 57
58 Overloading new & delete for arrays (Cont ) p = new Fred[n] code: char* tmp = (char*)operator new[](wordsize + n*sizeof(fred)); Fred* p = (Fred*) (tmp + WORDSIZE); *(size_t*)tmp = n; size_t i; try { for (i = 0; i < n; ++i) new(p + i) Fred(); // Placement new } catch (...) { while (i--!= 0) (p + i)->~fred(); // Explicit call to the destructor operator delete[] ((char*)p - WORDSIZE); throw; 58 }
59 Overloading new & delete for arrays (Cont ) Then the delete[] p statement becomes: // Original code: delete[] p; size_t n = *(size_t*)((char*)p-wordsize); while (n--!= 0) (p + n)->~fred(); operator delete[] ((char*)p - WORDSIZE); 59
60 Overloading new & delete for arrays (Cont ) Note that the address passed to operator delete[] is not the same as p. If you make a programming error by saying delete p where you should have said delete[] p, the address that is passed to operator delete(void*) is not the address of any valid heap allocation. This will probably corrupt the heap. 60
61 Overloading new & delete for arrays (Cont ) Using an "associative array" to remember the number of elements in an allocated array In this technique, the code for p = new Fred[n] looks something like this (where arraylengthassociation is the imaginary name of a hidden, global associative array that maps from void* to "size_t"): 61
62 Overloading new & delete for arrays (Cont ) Fred* p=(fred*)operator new[] (n * sizeof(fred)); size_t i; try { for (i = 0; i < n; ++i) new(p + i) Fred(); // Placement new } catch (...) { while (i--!= 0) (p + i)->~fred(); // Explicit call to the destructor operator delete[] (p); throw; } arraylengthassociation.insert(p, n); 62
63 Overloading new & delete for arrays (Cont ) Then the delete[] p statement becomes: size_t n=arraylengthassociation.lookup(p); while (n--!= 0) (p + n)->~fred(); operator delete[] (p); If you make a programming error by saying delete p where you should have said delete[] p, only the first Fred in the array gets destructed, but the heap may survive (unless you've replaced operator delete[] with something that doesn't simply call operator delete, or unless the destructors for the other Fred objects were necessary). 63
64 Overloading new & delete for arrays (Cont ) The Over-Allocation technique is faster, but more sensitive to the problem of programmers saying delete p rather than delete[] p. The associative array technique is slower, but less sensitive to the problem of programmers saying delete p rather than delete[] p. 64
65 coalescence Objects allocated at the same time tend to die at the same time. On average, after 2.5Kb of allocation, 90% of all objects have both neighbors free It pays to wait a short time after an object is freed. 65
66 Constructor calls MyType* f = new MyType; Assume we call new to allocate a MyTypesized piece of storage. This call invokes the MyType constructor on that storage. What happens if all the safeguards fail and the value returned by operator new is zero? 66
67 Constructor calls (Cont ) The constructor is not called in that case, so although you still have an unsuccessfully created object, at least you haven t invoked the constructor and handed it a zero pointer. 67
68 Constructor calls (Cont ) void my_new_handler() { cout << "new handler called" << endl; } class NoMemory { public: NoMemory() { cout << "NoMemory::NoMemory()" << endl; } }; 68 void* operator new(size_t sz) throw(bad_alloc) { cout << "NoMemory::operator new" << endl; //throw bad_alloc(); // "Out of memory" return 0; }
69 Constructor calls (Cont ) int main() { set_new_handler(my_new_handler); NoMemory* pnm = new NoMemory; cout << pnm = " << pnm << endl; } return 0; 69
70 placement new Used to construct an object on a pre-allocated storage. The overloaded operator new can take more than one argument. The first argument is always the size of the object, which is secretly calculated and passed by the compiler. The other arguments can be anything you want: the address you want the object placed at, a reference to a memory allocation function or object, or anything else that is convenient for you. The way you pass the extra arguments to operator new during a call may seem slightly curious at first: You put the argument list ( without the size_t argument, which is handled by the compiler) after the keyword new and before the class name of the object you re creating. 70
71 placement new (Cont ) class X { int i; public: X(int ii = 0) : i(ii) {} ~X() { cout << "X::~X()" << endl; } void* operator new(size_t, void* loc) { return loc; } }; int main() { int vec[10]; example 1: } X* xp = new(vec) X(47); // X at location vec xp->x::~x(); // Explicit destructor call // ONLY use with placement! return 0; 71
72 placement new (Cont ) class Data { public: int x; }; example 2: mini memory pool void* pmempool = malloc(256); void* pnextalloc = pmempool ; Data* pdata = new (pnextalloc) Data(); pnextalloc = (char*)(pnextalloc) + sizeof(data); // Writing to it pdata->x = 10; // Destroying c pdata->~data(); pnextalloc = (char*)(pnextalloc) - sizeof(data); free(pmempool); pmempool=null; pnextalloc=null; 72
73 placement new (Cont ) There s only one version of operator delete, so there s no way to say, Use my special de-allocator for this object. You want to call the destructor, but you don t want the memory to be released by the dynamic memory mechanism because it wasn t allocated on the heap. You can explicitly call the destructor, as in xp->x::~x(); // Explicit destructor call You will have serious problems if you call the destructor this way for an object created on the stack because the destructor will be called again at the end of the scope. If you call the destructor this way for an object that was created on the heap, the destructor will execute, but the memory won t be released, which probably isn t what you want. 73
74 nothrow new and delete extern const nothrow_t nothrow; This constant value is used as an argument for operator new and operator new[] to indicate that these functions shall not throw an exception on failure, but return a null pointer instead. This version cannot be replaced by the user. int main () { cout << "Attempting to allocate 1 MB..."; char* p = new (nothrow) char [ ]; if (p==0) cout << "Failed!\n"; else { cout << "Success!\n"; delete[] p; } return 0; } 74
75 summary The standard-provided overloads of operator new (there are also corresponding ones for array new[ ]): void* ::operator new( std::size_t size) throw(std::bad_alloc); // usual plain old boring new // usage: new T void* ::operator new( std::size_t size, const std::nothrow_t&) throw(); // nothrow new // usage: new (std::nothrow) T void* ::operator new(std::size_t size, void* ptr) throw(); // in-place (or "put-it-there") new // usage: new (ptr) T 75
Advanced Programming & C++ Language
Advanced Programming & C++ Language ~7~ Heap Management in C & C++ Ariel University 2018 Dr. Miri (Kopel) Ben-Nissan The Traditional Heap Manager 2 The standard C library routines for allocating and freeing
More informationMemory management. Johan Montelius KTH
Memory management Johan Montelius KTH 2017 1 / 22 C program # include int global = 42; int main ( int argc, char * argv []) { if( argc < 2) return -1; int n = atoi ( argv [1]); int on_stack
More informationMM1_ doc Page E-1 of 12 Rüdiger Siol :21
Contents E Structures, s and Dynamic Memory Allocation... E-2 E.1 C s Dynamic Memory Allocation Functions... E-2 E.1.1 A conceptual view of memory usage... E-2 E.1.2 malloc() and free()... E-2 E.1.3 Create
More informationEngine Support System. asyrani.com
Engine Support System asyrani.com A game engine is a complex piece of software consisting of many interacting subsystems. When the engine first starts up, each subsystem must be configured and initialized
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationException Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011
More C++ David Chisnall March 17, 2011 Exceptions A more fashionable goto Provides a second way of sending an error condition up the stack until it can be handled Lets intervening stack frames ignore errors
More informationA.Arpaci-Dusseau. Mapping from logical address space to physical address space. CS 537:Operating Systems lecture12.fm.2
UNIVERSITY of WISCONSIN-MADISON Computer Sciences Department CS 537 A. Arpaci-Dusseau Intro to Operating Systems Spring 2000 Dynamic Memory Allocation Questions answered in these notes When is a stack
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationAdvanced Programming & C++ Language
Advanced Programming & C++ Language ~6~ Introduction to Memory Management Ariel University 2018 Dr. Miri (Kopel) Ben-Nissan Stack & Heap 2 The memory a program uses is typically divided into four different
More informationDynamic Memory Management
Dynamic Memory Management 1 Goals of this Lecture Help you learn about: Dynamic memory management techniques Garbage collection by the run-time system (Java) Manual deallocation by the programmer (C, C++)
More informationCS61C : Machine Structures
inst.eecs.berkeley.edu/~cs61c/su06 CS61C : Machine Structures Lecture #6: Memory Management CS 61C L06 Memory Management (1) 2006-07-05 Andy Carle Memory Management (1/2) Variable declaration allocates
More informationObject-Oriented Programming for Scientific Computing
Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017
More informationDynamic Memory Management! Goals of this Lecture!
Dynamic Memory Management!!! 1 Goals of this Lecture! Help you learn about:! Dynamic memory management techniques! Garbage collection by the run-time system (Java)! Manual deallocation by the programmer
More informationCS 241 Honors Memory
CS 241 Honors Memory Ben Kurtovic Atul Sandur Bhuvan Venkatesh Brian Zhou Kevin Hong University of Illinois Urbana Champaign February 20, 2018 CS 241 Course Staff (UIUC) Memory February 20, 2018 1 / 35
More informationMotivation for Dynamic Memory. Dynamic Memory Allocation. Stack Organization. Stack Discussion. Questions answered in this lecture:
CS 537 Introduction to Operating Systems UNIVERSITY of WISCONSIN-MADISON Computer Sciences Department Dynamic Memory Allocation Questions answered in this lecture: When is a stack appropriate? When is
More informationDynamic Memory Allocation
Dynamic Memory Allocation CS61, Lecture 10 Prof. Stephen Chong October 4, 2011 Announcements 1/2 Assignment 4: Malloc Will be released today May work in groups of one or two Please go to website and enter
More informationHeap Management. Heap Allocation
Heap Management Heap Allocation A very flexible storage allocation mechanism is heap allocation. Any number of data objects can be allocated and freed in a memory pool, called a heap. Heap allocation is
More informationMemory Allocation. Static Allocation. Dynamic Allocation. Dynamic Storage Allocation. CS 414: Operating Systems Spring 2008
Dynamic Storage Allocation CS 44: Operating Systems Spring 2 Memory Allocation Static Allocation (fixed in size) Sometimes we create data structures that are fixed and don t need to grow or shrink. Dynamic
More informationHeap Management portion of the store lives indefinitely until the program explicitly deletes it C++ and Java new Such objects are stored on a heap
Heap Management The heap is the portion of the store that is used for data that lives indefinitely, or until the program explicitly deletes it. While local variables typically become inaccessible when
More informationCS 11 C track: lecture 5
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap Pointers (from last week) Address: location where data stored
More informationLecture 8 Dynamic Memory Allocation
Lecture 8 Dynamic Memory Allocation CS240 1 Memory Computer programs manipulate an abstraction of the computer s memory subsystem Memory: on the hardware side 3 @ http://computer.howstuffworks.com/computer-memory.htm/printable
More informationOptimizing Dynamic Memory Management
Optimizing Dynamic Memory Management 1 Goals of this Lecture Help you learn about: Details of K&R heap mgr Heap mgr optimizations related to Assignment #5 Faster free() via doubly-linked list, redundant
More informationCS61C : Machine Structures
inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 C Memory Management 2007-06-28 Scott Beamer, Instructor iphone Comes out Tomorrow CS61C L4 C Memory Management (1) www.apple.com/iphone
More informationCOSC345 Software Engineering. The Heap And Dynamic Memory Allocation
COSC345 Software Engineering The Heap And Dynamic Memory Allocation Outline Revision The programmer s view of memory Simple array-based memory allocation C memory allocation routines Virtual memory Swapping
More informationLaboratorio di Tecnologie dell'informazione
Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Exceptions What are exceptions? Exceptions are a mechanism for handling an error
More informationG52CPP C++ Programming Lecture 16
G52CPP C++ Programming Lecture 16 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Casting static cast dynamic cast const cast reinterpret cast Implicit type conversion 2 How
More informationCOMP6771 Advanced C++ Programming
1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout
More informationLecture Topics. Administrivia
ECE498SL Lec. Notes L8PA Lecture Topics overloading pitfalls of overloading & conversions matching an overloaded call miscellany new & delete variable declarations extensibility: philosophy vs. reality
More informationLectures 13 & 14. memory management
Lectures 13 & 14 Linked lists and memory management Courtesy of Prof. Garcia (UCB) CS61C L05 Introduction to C (pt 3) (1) Review Pointers and arrays are virtually same C knows how to increment pointers
More informationMemory Management. To do. q Basic memory management q Swapping q Kernel memory allocation q Next Time: Virtual memory
Memory Management To do q Basic memory management q Swapping q Kernel memory allocation q Next Time: Virtual memory Memory management Ideal memory for a programmer large, fast, nonvolatile and cheap not
More informationG52CPP C++ Programming Lecture 13
G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and
More informationCA341 - Comparative Programming Languages
CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data
More informationIn Java we have the keyword null, which is the value of an uninitialized reference type
+ More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC 330 - Spring 2013 1 Memory Attributes! Memory to store data in programming languages has the following lifecycle
More information10.1. CS356 Unit 10. Memory Allocation & Heap Management
10.1 CS356 Unit 10 Memory Allocation & Heap Management 10.2 BASIC OS CONCEPTS & TERMINOLOGY 10.3 User vs. Kernel Mode Kernel mode is a special mode of the processor for executing trusted (OS) code Certain
More informationCS 61C: Great Ideas in Computer Architecture C Memory Management, Usage Models
CS 61C: Great Ideas in Computer Architecture C Memory Management, Usage Models Instructors: Nicholas Weaver & Vladimir Stojanovic http://inst.eecs.berkeley.edu/~cs61c/sp16 1 Pointer Ninjitsu: Pointers
More informationC++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15
C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of dynamic memory allocation of variables and objects in a C++ program.
More informationCOSC Software Engineering. Lectures 14 and 15: The Heap and Dynamic Memory Allocation
COSC345 2013 Software Engineering Lectures 14 and 15: The Heap and Dynamic Memory Allocation Outline Revision The programmer s view of memory Simple array-based memory allocation C memory allocation routines
More information05-01 Discussion Notes
05-01 Discussion Notes PIC 10B Spring 2018 1 Exceptions 1.1 Introduction Exceptions are used to signify that a function is being used incorrectly. Once an exception is thrown, it is up to the programmer
More informationMidterm Review. PIC 10B Spring 2018
Midterm Review PIC 10B Spring 2018 Q1 What is size t and when should it be used? A1 size t is an unsigned integer type used for indexing containers and holding the size of a container. It is guarenteed
More informationException Handling Pearson Education, Inc. All rights reserved.
1 16 Exception Handling 2 I never forget a face, but in your case I ll make an exception. Groucho Marx It is common sense to take a method and try it. If it fails, admit it frankly and try another. But
More informationReview! Lecture 5 C Memory Management !
CS61C L05 C Memory Management (1)! inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 5 C Memory Management 2010-06-28!!! Instructor Paul Pearce! Symmetric multiprocessor! MIPS support for
More informationANITA S SUPER AWESOME RECITATION SLIDES
ANITA S SUPER AWESOME RECITATION SLIDES 15/18-213: Introduction to Computer Systems Dynamic Memory Allocation Anita Zhang, Section M UPDATES Cache Lab style points released Don t fret too much Shell Lab
More informationAcknowledgements These slides are based on Kathryn McKinley s slides on garbage collection as well as E Christopher Lewis s slides
Garbage Collection Last time Compiling Object-Oriented Languages Today Motivation behind garbage collection Garbage collection basics Garbage collection performance Specific example of using GC in C++
More informationCS61C : Machine Structures
inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 5 C Memory Management 2010-06-28!!! Instructor Paul Pearce! Symmetric multiprocessor! MIPS support for Android MIPS Technologies (founded
More informationLecture Material. Exceptions
Lecture Material Exceptions 1 Grouping of Exceptions Often, exceptions fall naturally into families. This implies that inheritance can be useful to structure exceptions and to help exception handling.
More informationCS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11
CS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11 CS 536 Spring 2015 1 Handling Overloaded Declarations Two approaches are popular: 1. Create a single symbol table
More informationMemory Management. q Basic memory management q Swapping q Kernel memory allocation q Next Time: Virtual memory
Memory Management q Basic memory management q Swapping q Kernel memory allocation q Next Time: Virtual memory Memory management Ideal memory for a programmer large, fast, nonvolatile and cheap not an option
More informationC++ Programming Lecture 4 Software Engineering Group
C++ Programming Lecture 4 Software Engineering Group Philipp D. Schubert VKrit Date: 24.11.2017 Time: 15:45 h Your opinion is important! Please use the free text comments Contents 1. Operator overloading
More informationWeek 5, continued. This is CS50. Harvard University. Fall Cheng Gong
This is CS50. Harvard University. Fall 2014. Cheng Gong Table of Contents News... 1 Buffer Overflow... 1 Malloc... 6 Linked Lists... 7 Searching... 13 Inserting... 16 Removing... 19 News Good news everyone!
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010
CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)
More informationThe issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management
Session 8 Memory Management The issues Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Programs manipulate data, which must be stored
More informationChapter 17 vector and Free Store. Bjarne Stroustrup
Chapter 17 vector and Free Store Bjarne Stroustrup www.stroustrup.com/programming Overview Vector revisited How are they implemented? Pointers and free store Allocation (new) Access Arrays and subscripting:
More information21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;
- 147 - Advanced Concepts: 21. Exceptions Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers.
More informationDynamic Memory Management
Dynamic Memory Management Professor Jennifer Rexford http://www.cs.princeton.edu/~jrex 1 Goals of Today s Lecture Dynamic memory management o Garbage collection by the run-time system (Java) o Manual deallocation
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC 330 Spring 2017 1 Memory Attributes Memory to store data in programming languages has the following lifecycle
More informationECE 598 Advanced Operating Systems Lecture 10
ECE 598 Advanced Operating Systems Lecture 10 Vince Weaver http://www.eece.maine.edu/~vweaver vincent.weaver@maine.edu 17 February 2015 Announcements Homework #1 and #2 grades, HW#3 Coming soon 1 Various
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many
More informationRecitation #11 Malloc Lab. November 7th, 2017
18-600 Recitation #11 Malloc Lab November 7th, 2017 1 2 Important Notes about Malloc Lab Malloc lab has been updated from previous years Supports a full 64 bit address space rather than 32 bit Encourages
More informationnptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n
Static and Dynamic Memory Allocation In this chapter we review the concepts of array and pointer and the use of the bracket operator for both arrays and pointers. We also review (or introduce) pointer
More informationIS 0020 Program Design and Software Tools
1 Introduction 2 IS 0020 Program Design and Software Tools Exception Handling Lecture 12 November 23, 200 Exceptions Indicates problem occurred in program Not common An "exception" to a program that usually
More informationCMSC 330: Organization of Programming Languages. Memory Management and Garbage Collection
CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC330 Fall 2018 1 Memory Attributes Memory to store data in programming languages has the following lifecycle
More informationIntroduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms
Introduction to Linked Lists Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms Lecture Slides Friday, September 25, 2009 Glenn G. Chappell Department of Computer Science
More informationPrinceton University Computer Science 217: Introduction to Programming Systems. Dynamic Memory Management
Princeton University Computer Science 217: Introduction to Programming Systems Dynamic Memory Management 1 Goals of this Lecture Help you learn about: The need for dynamic* memory mgmt (DMM) Implementing
More informationMemory Management. Didactic Module 14 Programming Languages - EEL670 1
Memory Management Didactic Module 14 Programming Languages - EEL670 1 Dynamic Memory Allocation Lots of things need memory at runtime: Activation records Objects Explicit allocations: new, malloc, etc.
More informationMemory Management. Chapter Fourteen Modern Programming Languages, 2nd ed. 1
Memory Management Chapter Fourteen Modern Programming Languages, 2nd ed. 1 Dynamic Memory Allocation Lots of things need memory at runtime: Activation records Objects Explicit allocations: new, malloc,
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 2 Thomas Wies New York University Review Last week Programming Languages Overview Syntax and Semantics Grammars and Regular Expressions High-level
More informationCS201 Some Important Definitions
CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data
More information377 Student Guide to C++
377 Student Guide to C++ c Mark Corner January 21, 2004 1 Introduction In this course you will be using the C++ language to complete several programming assignments. Up to this point we have only provided
More informationCS61C Midterm Review on C & Memory Management
CS61C Midterm Review on C & Memory Management Fall 2006 Aaron Staley Some material taken from slides by: Michael Le Navtej Sadhal Overview C Array and Pointer Goodness! Memory Management The Three Three
More informationDynamic Memory Allocation. Zhaoguo Wang
Dynamic Memory Allocation Zhaoguo Wang Why dynamic memory allocation? Do not know the size until the program runs (at runtime). #define MAXN 15213 int array[maxn]; int main(void) { int i, n; scanf("%d",
More informationPointers. Developed By Ms. K.M.Sanghavi
Pointers Developed By Ms. K.M.Sanghavi Memory Management : Dynamic Pointers Linked List Example Smart Pointers Auto Pointer Unique Pointer Shared Pointer Weak Pointer Memory Management In order to create
More informationModern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi
Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Using pointers Pointers are polymorphic Pointer this Using const with pointers Stack and Heap Memory leaks and dangling pointers
More informationCompiler Construction D7011E
Compiler Construction D7011E Lecture 14: Memory Management Viktor Leijon Slides largely by Johan Nordlander with material generously provided by Mark P. Jones. 1 First: Run-time Systems 2 The Final Component:
More informationSegmentation. Multiple Segments. Lecture Notes Week 6
At this point, we have the concept of virtual memory. The CPU emits virtual memory addresses instead of physical memory addresses. The MMU translates between virtual and physical addresses. Don't forget,
More informationHabanero Extreme Scale Software Research Project
Habanero Extreme Scale Software Research Project Comp215: Garbage Collection Zoran Budimlić (Rice University) Adapted from Keith Cooper s 2014 lecture in COMP 215. Garbage Collection In Beverly Hills...
More informationOperating System Labs. Yuanbin Wu
Operating System Labs Yuanbin Wu CS@ECNU Operating System Labs Project 2 Due 21:00, Oct. 24 Project 3 Group of 3 If you can not find a partner, drop us an email You now have 3 late days, but start early!
More informationVector and Free Store (Pointers and Memory Allocation)
DM560 Introduction to Programming in C++ Vector and Free Store (Pointers and Memory Allocation) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides
More information! What is main memory? ! What is static and dynamic allocation? ! What is segmentation? Maria Hybinette, UGA. High Address (0x7fffffff) !
Memory Questions? CSCI [4 6]730 Operating Systems Main Memory! What is main memory?! How does multiple processes share memory space?» Key is how do they refer to memory addresses?! What is static and dynamic
More informationCSCI-UA /2. Computer Systems Organization Lecture 19: Dynamic Memory Allocation: Basics
Slides adapted (and slightly modified) from: Clark Barrett Jinyang Li Randy Bryant Dave O Hallaron CSCI-UA.0201-001/2 Computer Systems Organization Lecture 19: Dynamic Memory Allocation: Basics Mohamed
More informationCS61, Fall 2012 Section 2 Notes
CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors
More informationProgramming Languages
Programming Languages Tevfik Koşar Lecture - VIII February 9 th, 2006 1 Roadmap Allocation techniques Static Allocation Stack-based Allocation Heap-based Allocation Scope Rules Static Scopes Dynamic Scopes
More informationStructure of Programming Languages Lecture 10
Structure of Programming Languages Lecture 10 CS 6636 4536 Spring 2017 CS 6636 4536 Lecture 10: Classes... 1/23 Spring 2017 1 / 23 Outline 1 1. Types Type Coercion and Conversion Type Classes, Generics,
More informationHeap Arrays. Steven R. Bagley
Heap Arrays Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index a[42] = 35; Variables and arrays have a type int, char, double,
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 10 October 1, 2018 CPSC 427, Lecture 10, October 1, 2018 1/20 Brackets Example (continued from lecture 8) Stack class Brackets class Main
More informationPrinceton University. Computer Science 217: Introduction to Programming Systems. Dynamic Memory Management
Princeton University Computer Science 217: Introduction to Programming Systems Dynamic Memory Management 1 Agenda The need for DMM DMM using the heap section DMMgr 1: Minimal implementation DMMgr 2: Pad
More informationPointers and References
Steven Zeil October 2, 2013 Contents 1 References 2 2 Pointers 8 21 Working with Pointers 8 211 Memory and C++ Programs 11 212 Allocating Data 15 22 Pointers Can Be Dangerous 17 3 The Secret World of Pointers
More informationCS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016
CS 31: Intro to Systems Pointers and Memory Martin Gagne Swarthmore College February 16, 2016 So we declared a pointer How do we make it point to something? 1. Assign it the address of an existing variable
More informationCS 345. Garbage Collection. Vitaly Shmatikov. slide 1
CS 345 Garbage Collection Vitaly Shmatikov slide 1 Major Areas of Memory Static area Fixed size, fixed content, allocated at compile time Run-time stack Variable size, variable content (activation records)
More informationA brief introduction to C++
A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne
More informationPrograms in memory. The layout of memory is roughly:
Memory 1 Programs in memory 2 The layout of memory is roughly: Virtual memory means that memory is allocated in pages or segments, accessed as if adjacent - the platform looks after this, so your program
More informationProcess s Address Space. Dynamic Memory. Backing the Heap. Dynamic memory allocation 3/29/2013. When a process starts the heap is empty
/9/01 Process s Address Space Dynamic Memory 0x7fffffff Stack Data (Heap) Data (Heap) 0 Text (Code) Backing the Heap When a process starts the heap is empty The process is responsible for requesting memory
More informationPointers II. Class 31
Pointers II Class 31 Compile Time all of the variables we have seen so far have been declared at compile time they are written into the program code you can see by looking at the program how many variables
More informationDeallocation Mechanisms. User-controlled Deallocation. Automatic Garbage Collection
Deallocation Mechanisms User-controlled Deallocation Allocating heap space is fairly easy. But how do we deallocate heap memory no longer in use? Sometimes we may never need to deallocate! If heaps objects
More informationClass Information ANNOUCEMENTS
Class Information ANNOUCEMENTS Third homework due TODAY at 11:59pm. Extension? First project has been posted, due Monday October 23, 11:59pm. Midterm exam: Friday, October 27, in class. Don t forget to
More informationUser created Heap Management in C on AIX
Nitin.Bagoria User Created Heap Management in C on AIX Page 1 of 9 User created Heap Management in C on AIX Introduction The term heap, or memory heap, generally means a free memory pool, from which a
More informationGEA 2017, Week 4. February 21, 2017
GEA 2017, Week 4 February 21, 2017 1. Problem 1 After debugging the program through GDB, we can see that an allocated memory buffer has been freed twice. At the time foo(...) gets called in the main function,
More information04-19 Discussion Notes
04-19 Discussion Notes PIC 10B Spring 2018 1 Constructors and Destructors 1.1 Copy Constructor The copy constructor should copy data. However, it s not this simple, and we need to make a distinction here
More informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
More informationRun-Time Environments/Garbage Collection
Run-Time Environments/Garbage Collection Department of Computer Science, Faculty of ICT January 5, 2014 Introduction Compilers need to be aware of the run-time environment in which their compiled programs
More information