1 / 18

Dynamic Allocation

Dynamic Allocation. Joe Meehean. Dynamic Allocation. Memory for local objects is automatically created and reclaimed memory is created for it at beginning of a function memory is reclaimed at the end of the function e.g., void func (){ int a = 7; if( a == 15 ){ a *= 2; } }

eugene
Télécharger la présentation

Dynamic Allocation

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Dynamic Allocation Joe Meehean

  2. Dynamic Allocation • Memory for local objects is automatically created and reclaimed • memory is created for it at beginning of a function • memory is reclaimed at the end of the function • e.g.,void func(){int a = 7; if( a == 15 ){ a *= 2; }} • It would be illegal to try to reference a (use its name) outside of the function func • What if we want objects that last longer?

  3. Dynamic Allocation • C++ provides a separate block of memory for this purpose • called the heap or free store • objects allocated (created from) the heap last until they are deallocated (explicitly returned to the heap) • heap allocated objects do not have names • we access them through pointers • Allocating this memory is called dynamic allocation • accomplished using the new operator • type *pointer_name = new type; • e.g.,int *pInt = new int;double *pdbl = new double;

  4. Dynamic Allocation 21 intaLocal = 21; int *pLocal = &aLocal; int *pHeap = new int; *pHeap = 34; aLocal pLocal 34 pHeap

  5. Dynamic Allocation • Initializing dynamically allocated objects • must use direct-initialization • e.g.,int *pInt = new int(1024);double* pDbl = new double(3.14);

  6. Dynamic Allocation • Deallocating heap objects • when we are done with an object we should return its memory to the heap • forgetting to deallocate heaps objects is called a memory leak • memory leaks cause programs to grow until they consume all of the machines memory and crash • delete operator • deallocates heap objects • delete pointer_name; • e.g.,int *pInt = new int(15);... delete pInt;

  7. Dynamic Allocation • What happens to pInt after it’s object has be deallocated? • pIntbecomes undefined, it is no longer valid • pInt points to memory is no longer owns • called a dangling pointer • Cleaning up dangling pointers • dangling pointers cause all sorts of programming errors • ALWAYS set a pointer to 0 (or NULL) after deallocating • e.g.,int *pInt = new int(15);...delete pInt;pInt = NULL;

  8. Dynamic Allocation • Calling delete on a zero-valued pointer is legal and safe • this is good in case you accidentally delete the same pointer twice • e.g.,int *pInt = new int(15);...delete pInt;pInt = NULL;...delete pInt;

  9. Dynamic Allocation • Dynamic allocation and const • legal to dynamically create constant objects • must be initialized when its created • cannot be changed once initialized • e.g.,constint*pInt = new int(15); • const heap objects also must be deallocated • e.g.,delete pInt;

  10. Dynamic Allocation • Common errors • Forgetting to delete dynamically allocated memory • causes memory leaks • Reading and writing to an object after it has been deleted • overwrites some other object’s memory • avoid by setting pointer to 0 after deleting • Deleting the same memory twice • two pointers may point at same heap object • deleting one pointer invalidates the other • calling delete on the other may corrupt the heap • big time bad news

  11. Dynamic Allocation & Arrays • What if we don’t know how many elements we need in an array until after we start running? • e.g., read in unknown number of items • do not know correct size get number of items from user • e.g.,we want to make a variable size tic-tac-toe board • can be 3x3, 4x4, NxN • do not know until user write size on the console • “Enter Board Size: “

  12. Dynamic Allocation & Arrays • Dynamic allocation of arrays solves this problem • heap can allocate memory at run time based on a variable size • type *array_name = new type[dimension] • returns a pointer to the first element in the array • e.g., int*pIntArray = new int[15]; • Must deallocate later • just like other dynamic allocations • syntax slightly different • delete [] array_name;

  13. Dynamic Allocation & Arrays // ask user for input cout << "What is the largest prime to find?“; cout<< endl; // get user input size_tmax_prime; cin >> max_prime; max_prime++; // i'th entry stores whether number i is a prime bool*potential_prime = new bool[max_prime]; //run the sieve … // clean up the memory delete [] potential_prime;

  14. Dynamic Allocation & Arrays • Dynamic allocation of multidimensional arrays • dynamically allocate an array • each element of 1st array stores pointers a row • row is a dynamically allocated array of columns 1 2 3 4 5 6 7 8 9 10 11 12

  15. Dynamic Allocation & Arrays • Dynamic allocation of multidimensional arrays int **matrix = new int*[rows]; for(inti = 0; i < rows; i++){ matrix[i] = new int[columns]; }

  16. Dynamic Allocation & Arrays • Dynamic allocation of multidimensional arrays int count = 1; for(inti = 0; i < rows; i++){ for(int j = 0; j < columns; j++){ matrix[i][j]= count; count++; } } 1 2 3 4 5 6 7 8 9 10 11 12

  17. Dynamic Allocation & Arrays • Dynamic allocation of multidimensional arrays • need to deallocate all dynamically allocated memory • deallocate each row • then, deallocate the array that stored row pointers for(inti = 0; i < rows; i++){ delete [] matrix[i]; } delete [] matrix;

  18. Questions?

More Related