C++: Memory Problems Logistics Logistics Plan for This Week Memory

C++: Memory Problems Logistics Logistics Plan for This Week Memory

Logistics • Project C++: Memory Problems – Part 2 (water) due Sunday, Oct 16th • Questions? or When Good Memory Goes Bad Logistics Plan for this week • Final exam • Today: Intro to Memory Management – Good news…bad news • Tomorrow: Memory Problems – Good news • Thursday: Standard Libraries • Last day of finals, November 18th –Bad news • 8am-10am – Room • 01-3338 Memory Leak Memory Leak • A bug in a program that prevents it from class Foo freeing up memory that it no longer needs. { private: • As a result, the program grabs more and int *array_member; more memory until it finally crashes int asize; because there is no more memory left. ... public: • In short: Foo (int size); – Allocating without cleaning up. ~Foo (); } 1 Memory Leak Memory Leak Foo::Foo (int size) : asize (size), array_member (new int[size]) { for (int i=0; i<size; i++) asize array_member[i] = 0; aClass a array_member } 20 ints void f () { // local aClass object stack aClass a (20); ... } heap Pointer Ownership Pointer Ownership • Everything that is a pointer should be • Class members owned – If you allocate it during construction, you – Responsible for cleanup when finished should deallocate during destruction. – Should be known to programmer – Should be by design during implementation. – Should also deallocate during • Copy construction • operator= – Owner and only owner should perform a delete. Pointer Ownership Pointer Ownership // constructor // copy constructor Foo::Foo (int size) : Foo::Foo (const Foo &F) asize (size), array_member (new int[size]) { { if (F != (*this) { for (int i=0; i<size; i++) array_member[i] = 0; delete [] array_member; } array_member = new int[F.asize]; asize = F.asize; // destructor Foo:~Foo () for (int i=0; i<asize; i++) { array_member[i] = F.array_member[i]; delete [] array_member; } } } 2 Pointer Ownership Pointer Ownership // assignment operator Foo &Foo::operator= (const Foo &F) • Pointers returned by functions { – Who should be responsible for memory to if (F != (*this) { delete [] array_member; which these pointers point? array_member = new int[F.asize]; asize = F.asize; for (int i=0; i<asize; i++) array_member[i] = F.array_member[i]; } return (*this); } Pointer Ownership Pointer Ownership class Moo Allocation done in method…caller should be { responsible for pointer. private: char* myID static char anotherId[15]; char * Moo::getID() ... { public: char *id = new char[15]; Moo (); strcpy (id, “I am a cow”); ... char *getID(); return id; } } Pointer Ownership Pointer Ownership Allocation done in constructor…object should be responsible Memory is static…object should be responsible for for pointer….should deallocate in destructor pointer but no deallocation necessary Moo::Moo () : myID (new char[15]) { char Moo::anotherID[15] = “I am a cow”; strcpy (id, “I am a cow”); } char * Moo::getID() char * Moo::getID() { { return anotherID; return myID; } } 3 Pointer Ownership Pointer Ownership Memory is static…object should be responsible for Should not return pointer to local variable pointer but no deallocation necessary char * Moo::getID() char * Moo::getID() { { // This is okay too. // This is not okay. static char idInFunct[50] = “I am a char idInFunct[50] = “I am a cow”; cow”; return idInFunct; return idInFunct; } } Pointer Ownership Pointer Ownership • Pointers returned by functions • Anonymous Objects – Who should be responsible for memory to – An anonymous object is an object in every which these pointers point? sense except that it has no name. • Either caller or object – Used for creating very temporary objects. • Should be clearly designed and documented Point square[] = {Point(0,0),Point(0,1),Point(1,1),Point(1,0) }; Memory Leak / Pointer Pointer Ownership Ownership • Anonymous Objects • Questions? – Beware when anonymous objects are allocated on free store. vector< Card * > hand; hand.push_back( new Card(...) ); hand.push_back( new Card(...) ); hand.push_back( new Card(...) ); : : If vector does not take ownership of the objects stored in it, a memory leak is possible. 4 Dangling Pointers Dangling Pointers • Pointer is pointing to something that it p1 = new Foo; shouldn’t be. : delete p1; • Can happen if: : – If the scope of a pointer extends beyond that of p2 = new Bar; // What if same memory is the object being pointed to //given to p2? • i.e Returning a pointer to a local variable. : – If a dynamically allocated memory cell is freed int i = p1->data; // i contains garbage explicitly and then the pointer pointing to such a space is used in subsequent code. p1->op(...); // p2's object mysteriously changes! Dangling Pointers Dangling Pointer / Double delete c1 • Ways to prevent dangling pointers class Foo { – Do not return pointers to local variables. private: – After calling delete on a pointer, int immediately set it to NULL. *array_member; int asize; ... p1 = new Foo; } c2 delete p1; void moo () p1 = 0; { p2 = new Bar; Foo c1, c2; Free p1->op(...); // core dump! c1 = c2; store } Aka premature deletion Bounds errors Bounds errors • Recall that C++ has no array bounds void foo() { checking. int *a = new int[20]; – Writing past bounds of array will trash aClass *b = new aClass(); unsuspecting memory. ... a a[20] = 23; // b mysteriously // changes } b heap 5 Bounds errors Bounds errors void foo() • This can be quite dangerous for local arrays: Local Variables { int a[20]; a[20] = 23; a Local Variables } Return Address Return Address Function Arguments Function Arguments Dangling Pointers / Bounds errors Bounds errors void foo() • Questions? { char a[20]; strcpy (a, “This string is too long”); } Getting around these problems The Smart Pointer • The smart pointer Smart pointer – Prevents memory leaks and dangling pointers – Wrapper class that owns a pointer to an object ptr • Object keeps a reference count of variables accessing it • When the reference count reaches 0, the object is deleted by the smart pointer. • After deleting object, pointer value set to 0. 6 The Smart Pointer Using smart pointers • The smart pointer should look and act Instead of Use like a regular pointer: – Should support -> void foo() void foo() – Should support * { { MyClass* p(new MyClass); SmartPtr<MyClass> • Should be smarter than your average pointer. p->DoSomething(); p(new MyClass); delete p; p->DoSomething(); – Reduce memory leaks } } – Reduce dangling pointers – Take ownership p will cleanup after itself Smart Pointers Summary • We may be looking at the details of a smart • Memory Woes pointer in Week 9/10 – Memory leak – Dangling Pointer • There is a Smart Pointer class available for use on the project • Double Delete( aka Premature delete) – See choices.html of of Project pages – Pointer Ownership – Overwrite array • Questions? Tomorrow’s Lab • Inheritance • Memory Management Lab in 2 weeks. 7.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    7 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us