When ownership of memory must be very clearly

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ts Memory must be freed differently depending on how it was allocated: malloc <-> free new new <-> <-> delete delete How to Remember to Free Unused Memory Whenever you write a piece of code alloca6ng some memory, you already must be thinking about who will free it, where and when Ownership of memory must be very clearly understood DESCRIPTION The strdup() func6on allocates sufficient memory for a copy of the string s1, does the copy, and returns a pointer to it. The pointer may subsequently be used as an argument to the func6on free(3). With strdup, it is clear that the caller owns the returned memory So What’s Wrong With This Code? struct Point { int x; int y; } Point* foo(int x, int y) { Point p; p.x = x; p.y = y; return &p; } void bar() { Point* point = foo(1,2); delete point; } So What’s Wrong With This Code? struct Point { int x; int y; } Point* foo(int x, int y) { Point p; p.x = x; p.y = y; return &p; // uh-oh, returning a pointer to stack// allocated memory. big no-no. } void bar() { Point* point = foo(1,2); delete point; } So What’s Wrong With This Code? struct Point { int x; int y; } void foo(int x, int y, Point* p) { p->x = x; p->y = y; } void bar() { Point point; foo(1,2, &point); } struct Point { int x; int y; } Point* foo(int x, int y) { Point* p = new Point(); p->x = x; p->y = y; return p; } void bar() { Point p = foo(1,2); delete p; } Finding Memory Leaks Very useful and easy ­to ­use tool on Unix ­based plalorms (including CSIF): valgrind Usage: valgrind [op,ons] <prog ­and ­args> Will tell you if you’ve leaked memory, and where it was allocated We’ll use this in the warmup homework, and in grading your project components Smart Pointers: a Useful C++ Idiom for Memory Management Basic idea: instead of working with “raw” pointer, like Foo* ptr = new Foo(1); ptr = new Foo(2); // oops, leaked the first object work with a “wrapped” version that automa6cally frees the underlying object when leaving scope std::auto_ptr<Foo> ptr = new Foo(1); ptr = new Foo(2); // first object deleted automatically // on assignment Smart Pointers: Pros and Cons Pros: automates away much of the grunt work of memory management; great...
View Full Document

This document was uploaded on 03/12/2014 for the course CSCI 165B at UC Davis.

Ask a homework question - tutors are online