473,386 Members | 1,860 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Memory Cleanup problem

Moving to C++ from Java, I'm still confused by some aspects of memory
cleanup operations.

For example, let's say I have a class MovingObject which maintains a
pointer to another class MovementAlgorithm.

MovingObject has a method
SetMovementAlgorithm(MovementAlgorithm* movementAlgorithm)

if the body of this method reads
{
this->movementAlgorithm = movementAlgorithm;
}

is this a memory leak every time a new MovementAlgorithm is set (other
than the first time)? Because the previous movement algorithm isn't
deleted?

What is the correct way to handle this problem?

If I change the body of the method to read as follows :

if (this->movementAlgorithm != NULL) {
delete this->movementAlgorithm;
}
this->movementAlgorithm = movementAlgorithm;

I get program crash. All of the constructors for MovingObject
initialize the pointer variable either to NULL or through the new
operator. Can anyone explain this?
Jul 22 '05 #1
10 1907
On Sat, 31 Jul 2004 18:58:25 +0100, Jonathan Ames <am**@reb.org> wrote:
Moving to C++ from Java, I'm still confused by some aspects of memory
cleanup operations.

For example, let's say I have a class MovingObject which maintains a
pointer to another class MovementAlgorithm.

MovingObject has a method
SetMovementAlgorithm(MovementAlgorithm* movementAlgorithm)

if the body of this method reads
{
this->movementAlgorithm = movementAlgorithm;
}

is this a memory leak every time a new MovementAlgorithm is set (other
than the first time)? Because the previous movement algorithm isn't
deleted?
There is no memory leak here because there is no memory allocated here,
it's the way that you *use* SetMovementAlgorithm that causes the memory
leak.

I think you are using it something like this

MovingObject x;
x.SetMovementAlgorithm(new MovementAlgorithm); // 1
....
x.SetMovementAlgorithm(new MovementAlgorithm); // 2

Here there is a memory leak, because the only pointer pointing to the
object allocated at step 1 has been overwritten at step 2, and so that
object can never be deleted.

But in this similar code there is no memory leak

MovingObject x;
MovementAlgorithm y1;
x.SetMovementAlgorithm(&y1);
....
MovementAlgorithm y2;
x.SetMovementAlgorithm(&y2);

What is the correct way to handle this problem?

It depends.
If I change the body of the method to read as follows :

if (this->movementAlgorithm != NULL) {
delete this->movementAlgorithm;
}
this->movementAlgorithm = movementAlgorithm;

I get program crash. All of the constructors for MovingObject
initialize the pointer variable either to NULL or through the new
operator. Can anyone explain this?


Not without seeing more code. I guess the most likely reason for the crash
is that you are deleteing the same memory twice because you have not
defined a suitable copy constructor or assignment operator for the class
MovingObject. When a MovingObject object is copied you are copying the
movementAlgorithm data member and hence end up deleting the same memory
twice. But that is only a guess.

The solution to all these problems is to use pointer in a less cavalier
fashion. I don't know exactly what you are tring to achieve but here are
some suggestions.

1) To you really need to use pointers at all? Could you not define
MovingObject like this

class MovingObject
{
...
MovementAlgorithm movementAlgorithm;
};

2) If you really do need pointers then read up on the 'rule of three'. as
soon as you include a pointer in a class you almost always need to define
proper copy constructors and assignment operators for that class. I
suspect that you are not doing that, although I don't know because you
didn't post the code.

3) As soon as you start allocating objects using new, then you must think
about whose responsiblity it is to free that pointer. In other words who
owns the pointer. The way you have described your MovingObject class so
far it sounds as if the MovementAlgorithm object is allocated outside the
MovingObject class but a MovingObject object takes ownership of the
pointer when SetMovementAlgorithm is called. Are you happy and clear about
that?

4) Learn about smart pointers, which take care of many of the problems in
correctly freeing allocated objects automatically. For instance have a
look at the shared_ptr class available from boost
http://www.boost.org/libs/smart_ptr/smart_ptr.htm. It could be exactly
what you need.

If all this doesn't help then post the definitions for Movingbject and
MovementAlgorithm and I'll take another look.

john
Jul 22 '05 #2
"Jonathan Ames" <am**@reb.org> wrote...
Moving to C++ from Java, I'm still confused by some aspects of memory
cleanup operations.

For example, let's say I have a class MovingObject which maintains a
pointer to another class MovementAlgorithm.

MovingObject has a method
SetMovementAlgorithm(MovementAlgorithm* movementAlgorithm)

if the body of this method reads
{
this->movementAlgorithm = movementAlgorithm;
}

is this a memory leak every time a new MovementAlgorithm is set (other
than the first time)? Because the previous movement algorithm isn't
deleted?
Probably. That is, if 'movementAlgorithm' in fact _was_ allocated by
somebody using 'new'. A 'MovingObject' apparently takes ownership of
the pointer (and is responsible for releasing the memory from there on)
so if you simply copy the value, the previous value is usually lost.

What is the correct way to handle this problem?
Depends on the situation.

If I change the body of the method to read as follows :

if (this->movementAlgorithm != NULL) {
delete this->movementAlgorithm;
There is no need for the 'if' here. 'delete NULL' does nothing.
}
this->movementAlgorithm = movementAlgorithm;

I get program crash.
It is more likely because the memory to which the 'movementAlgorithm'
points when you try to delete it, wasn't allocated using 'new'.
All of the constructors for MovingObject
initialize the pointer variable either to NULL or through the new
operator. Can anyone explain this?


I could guess. If all of them were in fact allocated using 'new',
then the problem can be in deleting the same object more than once.
Of course, it's just as good a guess as anybody else's who hasn't
seen the complete code.

C++ pointers are tricky. Pointers to dynamically allocated object
are even trickier. They require a lot of attention. That's why it
is often recommended that beginners don't use them.

Victor
Jul 22 '05 #3
On 7/31/2004 7:58 PM, Jonathan Ames wrote:
if the body of this method reads
{
this->movementAlgorithm = movementAlgorithm;
}

is this a memory leak every time a new MovementAlgorithm is set (other
than the first time)? Because the previous movement algorithm isn't
deleted?
If the first MovementAlgorithm object was created dynamicaly on the
heap somewhere in your program, you have to place somewhere delete
action on it, because leaks will occur.

So, one of the possible solution would be to check if
the local member of MovingObject (pointer to MovementAlgorithm)
is null or not:

{
// Destroy existing algo. object
if (this->movementAlgorithm != NULL)
delete this->movementAlgorithm;

// Assign new one
this->movementAlgorithm = movementAlgorithm;
}

But you have to track movementAlgorithm member NULL'ity,
I mean you have to assign NULL to it in MovingObject constructor
or initialization list and if you don't assign new algo. but you have
i.e. method called DetachAlgoFromMovingObject(); which clears
it you have to again assign NULL so when you assign new algo.
to the object again, NULL'ity of MovingObject assumption will
be true, so no destruction of algorithm will be performed.

I don't know your all code but I think that the statement
this->myPointer is on oe Java habit ;-)
If you don't have any pointer casts (to base or derived class)
and dynamic (virtual) polymorphism I think
that you can simply write the code above this way:

{
// Destroy existing algo. object
if (movementAlgorithm != NULL)
delete this->movementAlgorithm;

// Assign new one
movementAlgorithm = movementAlgorithm;
}

What is the correct way to handle this problem?
The above is only my idea, but I don't guarantee it is the
most correct way.
If I change the body of the method to read as follows :

if (this->movementAlgorithm != NULL) {
delete this->movementAlgorithm;
}
this->movementAlgorithm = movementAlgorithm;
Hehehehe !
I've just seen it ;-)) after I wrote my idea, so
I leave it and post on group but it's funny.
I didn't read whole your post before I write my answer ;-)
I get program crash. All of the constructors for MovingObject
initialize the pointer variable either to NULL or through the new
operator. Can anyone explain this?


You have to assign NULL to pointers by yourself.
There is know default constructor for pointer which would
do it for you.

Greets

--

Mateusz Łoskot
mateusz at loskot dot net
Jul 22 '05 #4
On 7/31/2004 8:24 PM, Victor Bazarov wrote:
If I change the body of the method to read as follows :

if (this->movementAlgorithm != NULL) {
delete this->movementAlgorithm;


There is no need for the 'if' here. 'delete NULL' does nothing.


It's new information for me ;-)
Thanks a lot. It seems to be obvious but untill now I thought
deleting null will couse some not-defined state of program.

Thanks ;-))
--

Mateusz Łoskot
mateusz at loskot dot net
Jul 22 '05 #5
"John Harrison" <jo*************@hotmail.com> wrote in message
news:opsb0k3qjt212331@andronicus...
On Sat, 31 Jul 2004 18:58:25 +0100, Jonathan Ames <am**@reb.org> wrote:

I think you are using it something like this

MovingObject x;
x.SetMovementAlgorithm(new MovementAlgorithm); // 1
...
x.SetMovementAlgorithm(new MovementAlgorithm); // 2


Which is a major stumbling block for most Java programmers that I've come in
contact with who are learning C++. They "new" everything under the sun in
their C++ programs, thinking that "new" in C++ means the same thing as "new"
in Java.

Since in Java, every object, except the basic types, must be created using
"new", they believe the same thing is the case for C++. I've cringed when
I've taken a look at some C++ programs written by Java programmers...

Paul
Jul 22 '05 #6
On Sun, 01 Aug 2004 04:22:48 GMT, Paul <pa**@paul.com> wrote:
"John Harrison" <jo*************@hotmail.com> wrote in message
news:opsb0k3qjt212331@andronicus...
On Sat, 31 Jul 2004 18:58:25 +0100, Jonathan Ames <am**@reb.org> wrote:

I think you are using it something like this

MovingObject x;
x.SetMovementAlgorithm(new MovementAlgorithm); // 1
...
x.SetMovementAlgorithm(new MovementAlgorithm); // 2


Which is a major stumbling block for most Java programmers that I've
come in
contact with who are learning C++. They "new" everything under the sun
in
their C++ programs, thinking that "new" in C++ means the same thing as
"new"
in Java.

Since in Java, every object, except the basic types, must be created
using
"new", they believe the same thing is the case for C++. I've cringed
when
I've taken a look at some C++ programs written by Java programmers...

Paul


Not only that, but also the lack of consideration for pointer ownership
issues. Not surprisingly, when you've been spoilt with Java's garbage
collection, it's a big adjustment when you start coding C++.

I wonder if there is a good C++ for Java programmers book to recommend.

John
Jul 22 '05 #7
On 8/1/2004 10:01 AM, John Harrison wrote:
I wonder if there is a good C++ for Java programmers book to recommend.


I know one book touching this topic:

"Programming with Objects: A Comparative Presentation of Object-Oriented
Programming with C++ and Java"

by Avinash C. Kak

ISBN:0471268526

John Wiley & Sons (c) 2003 (1115 pages)
I haven't read it but I know it is on the market.
The title suggest it explains the differences between
C++ and Java and instructs how to solve some problems in
C++ in comparsion to Java.

Greets

--

Mateusz Łoskot
mateusz at loskot dot net
Jul 22 '05 #8
Paul wrote:
"John Harrison" <jo*************@hotmail.com> wrote in message
news:opsb0k3qjt212331@andronicus...
On Sat, 31 Jul 2004 18:58:25 +0100, Jonathan Ames <am**@reb.org> wrote:

I think you are using it something like this

MovingObject x;
x.SetMovementAlgorithm(new MovementAlgorithm); // 1
...
x.SetMovementAlgorithm(new MovementAlgorithm); // 2


Which is a major stumbling block for most Java programmers that I've come in
contact with who are learning C++. They "new" everything under the sun in
their C++ programs, thinking that "new" in C++ means the same thing as "new"
in Java.

Since in Java, every object, except the basic types, must be created using
"new", they believe the same thing is the case for C++. I've cringed when
I've taken a look at some C++ programs written by Java programmers...


It is unfortunate the designers of the Java language choose a syntax
similar to C++. The different semantics combined with similar syntax
makes the crossover between these two languages unnecessarily hard.

--
Peter van Merkerk
peter.van.merkerk(at)dse.nl
Jul 22 '05 #9
On Sat, 31 Jul 2004 18:58:25 +0100, Jonathan Ames <am**@reb.org>
wrote:
Moving to C++ from Java, I'm still confused by some aspects of memory
cleanup operations.

For example, let's say I have a class MovingObject which maintains a
pointer to another class MovementAlgorithm.

MovingObject has a method
SetMovementAlgorithm(MovementAlgorithm* movementAlgorithm)

if the body of this method reads
{
this->movementAlgorithm = movementAlgorithm;
}

is this a memory leak every time a new MovementAlgorithm is set (other
than the first time)? Because the previous movement algorithm isn't
deleted?

What is the correct way to handle this problem?

If I change the body of the method to read as follows :

if (this->movementAlgorithm != NULL) {
delete this->movementAlgorithm;
}
this->movementAlgorithm = movementAlgorithm;

I get program crash. All of the constructors for MovingObject
initialize the pointer variable either to NULL or through the new
operator. Can anyone explain this?


Thanks all for the replies. They were very helpful. I've solved the
immediate problem and now realise that I have some further studying
and reflecting to do on my use of C++ idioms.

Jul 22 '05 #10
In message <1i********************************@4ax.com>, Jonathan Ames
<am**@reb.org> writes
On Sat, 31 Jul 2004 18:58:25 +0100, Jonathan Ames <am**@reb.org>
wrote:
Moving to C++ from Java, I'm still confused by some aspects of memory
cleanup operations.

For example, let's say I have a class MovingObject which maintains a
pointer to another class MovementAlgorithm.

MovingObject has a method
SetMovementAlgorithm(MovementAlgorithm* movementAlgorithm)

if the body of this method reads
{
this->movementAlgorithm = movementAlgorithm;
}

is this a memory leak every time a new MovementAlgorithm is set (other
than the first time)? Because the previous movement algorithm isn't
deleted?

What is the correct way to handle this problem?

If I change the body of the method to read as follows :

if (this->movementAlgorithm != NULL) {
delete this->movementAlgorithm;
}
this->movementAlgorithm = movementAlgorithm;

I get program crash. All of the constructors for MovingObject
initialize the pointer variable either to NULL or through the new
operator. Can anyone explain this?


Thanks all for the replies. They were very helpful. I've solved the
immediate problem and now realise that I have some further studying
and reflecting to do on my use of C++ idioms.

And perhaps the first one you should be researching goes by the name of
"smart pointer". Depending on your needs, one of std::auto_ptr,
boost::shared_ptr and boost::scoped_ptr may well have something to
offer.

--
Richard Herring
Jul 22 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: J. Campbell | last post by:
what happens to allocated memory when a program terminates before the memory is released. For example: int main(){ int* array; int a_size = 1000; array = new int; for(int i = 0; i < a_size;...
5
by: Jason Callas | last post by:
I was doing starting some experimenting with the GC and ran into the following odd result. I created an object and my used memory went up by almost 11k but when I cleared it and forced a collection...
3
by: ReGenesis0 | last post by:
I'm trying to rewrite the existing window using javascript. This works fine in IE- but in Mozilla, after I call a window.open, Mozilla starts wandering around like an alshiemers patient and...
19
by: Jon Davis | last post by:
I'm reposting this because I really need some advice. I have a web app that makes many queries to the database on every page. In order to save development effort, I've consolidated all database...
13
by: Bob | last post by:
I have been working on the following program. The goal is to have a tokenizing routine that avoids some of the problems of strtok(), the comments should explain the features. This runs fine on...
7
by: ballpointpenthief | last post by:
Hello, I'm thinking that it would be a good idea to start using the return code for main() to return the amount of memory still allocated (which would hopefully be zero) to ensure all memory has...
26
by: Bill Reid | last post by:
Bear with me, as I am not a "professional" programmer, but I was working on part of program that reads parts of four text files into a buffer which I re-allocate the size as I read each file. I...
34
by: jacob navia | last post by:
Suppose that you have a module that always allocates memory without ever releasing it because the guy that wrote it was lazy, as lazy as me. Now, you want to reuse it in a loop. What do you do?...
6
by: Peter Michaux | last post by:
I just ran some circular memory leak tests in IE6, O9, S3, FF2 and it seems to me they all benefit from doing the same kind of circular memory leak cleanup that IE requires. My tests were very...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.