Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pointer/Memory Leak Challenge

Status
Not open for further replies.

rousse

Programmer
Sep 24, 2003
12
0
0
US
Hello,
Can anyone find what the (memory leak) problem is in this code segment:
--------------------------
void
foo1( void )
{
A *a = appArray.iterate( 0 );
B *b;

b = new B;
...
b = foo2( a->id );
...
delete b;
}

Note that foo2 returns B*
---------------------------
Thank you.
 
The exact same answer I gave you back in the C forum.

new dynamically allocates memory. That memory never gets released.
 
Aside from the memory leak, you are also deleting a statically allocated object, so when it's destructor is called you'll segfault (assuming that foo2 returns the aadress of a static object). akin to
Code:
void main()
{ 
int A = 5;
int *a = &A;
delete a;
}
 
Or looking at the whole thing another way,

b = new B;

creates a "B" and points to it using "b". Later you need to free that "B" before changing the pointer to point to a different object. This is what "delete b;" does.

... some code to use the first B pointed to by "b"
delete b; // delete the first B pointed to by "b"
// Now we create a new object and point "b" to it
b = foo(<some function which new's a B>)
... some code to use the second B pointed to by &quot;b&quot;
delete b; // delete the second B pointed to by &quot;b&quot;

personally I use auto_ptr<> if I HAVE to use pointers but usually I try to create the objects locally on the stack rather than &quot;new&quot;ing them.

Other things to think about:

1) try getting used to using references rather than pointers and pass them around rather than pointers.

2) wrap dynamic memory allocation in a class which cleans it up in the destructor and then allocate that wrapper class as a local variable.
:)
 
Or just write in Java.... :p
Pointers are fun. I think the parent poster had a good challenge, Programming II here has a Lab sorta like that.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top