473,809 Members | 2,797 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 MovementAlgorit hm.

MovingObject has a method
SetMovementAlgo rithm(MovementA lgorithm* movementAlgorit hm)

if the body of this method reads
{
this->movementAlgori thm = movementAlgorit hm;
}

is this a memory leak every time a new MovementAlgorit hm 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->movementAlgori thm != NULL) {
delete this->movementAlgori thm;
}
this->movementAlgori thm = movementAlgorit hm;

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 1942
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 MovementAlgorit hm.

MovingObject has a method
SetMovementAlgo rithm(MovementA lgorithm* movementAlgorit hm)

if the body of this method reads
{
this->movementAlgori thm = movementAlgorit hm;
}

is this a memory leak every time a new MovementAlgorit hm 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* SetMovementAlgo rithm that causes the memory
leak.

I think you are using it something like this

MovingObject x;
x.SetMovementAl gorithm(new MovementAlgorit hm); // 1
....
x.SetMovementAl gorithm(new MovementAlgorit hm); // 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;
MovementAlgorit hm y1;
x.SetMovementAl gorithm(&y1);
....
MovementAlgorit hm y2;
x.SetMovementAl gorithm(&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->movementAlgori thm != NULL) {
delete this->movementAlgori thm;
}
this->movementAlgori thm = movementAlgorit hm;

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
movementAlgorit hm 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
{
...
MovementAlgorit hm movementAlgorit hm;
};

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 MovementAlgorit hm object is allocated outside the
MovingObject class but a MovingObject object takes ownership of the
pointer when SetMovementAlgo rithm 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
MovementAlgorit hm 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 MovementAlgorit hm.

MovingObject has a method
SetMovementAlgo rithm(MovementA lgorithm* movementAlgorit hm)

if the body of this method reads
{
this->movementAlgori thm = movementAlgorit hm;
}

is this a memory leak every time a new MovementAlgorit hm is set (other
than the first time)? Because the previous movement algorithm isn't
deleted?
Probably. That is, if 'movementAlgori thm' 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->movementAlgori thm != NULL) {
delete this->movementAlgori thm;
There is no need for the 'if' here. 'delete NULL' does nothing.
}
this->movementAlgori thm = movementAlgorit hm;

I get program crash.
It is more likely because the memory to which the 'movementAlgori thm'
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->movementAlgori thm = movementAlgorit hm;
}

is this a memory leak every time a new MovementAlgorit hm is set (other
than the first time)? Because the previous movement algorithm isn't
deleted?
If the first MovementAlgorit hm 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 MovementAlgorit hm)
is null or not:

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

// Assign new one
this->movementAlgori thm = movementAlgorit hm;
}

But you have to track movementAlgorit hm 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 DetachAlgoFromM ovingObject(); 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 (movementAlgori thm != NULL)
delete this->movementAlgori thm;

// Assign new one
movementAlgorit hm = movementAlgorit hm;
}

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->movementAlgori thm != NULL) {
delete this->movementAlgori thm;
}
this->movementAlgori thm = movementAlgorit hm;
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->movementAlgori thm != NULL) {
delete this->movementAlgori thm;


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:opsb0k3qjt 212331@andronic us...
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.SetMovementAl gorithm(new MovementAlgorit hm); // 1
...
x.SetMovementAl gorithm(new MovementAlgorit hm); // 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.co m> wrote:
"John Harrison" <jo************ *@hotmail.com> wrote in message
news:opsb0k3qjt 212331@andronic us...
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.SetMovementAl gorithm(new MovementAlgorit hm); // 1
...
x.SetMovementAl gorithm(new MovementAlgorit hm); // 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:

"Programmin g 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:opsb0k3qjt 212331@andronic us...
On Sat, 31 Jul 2004 18:58:25 +0100, Jonathan Ames <am**@reb.org > wrote:

I think you are using it something like this

MovingObjec t x;
x.SetMovement Algorithm(new MovementAlgorit hm); // 1
...
x.SetMovement Algorithm(new MovementAlgorit hm); // 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.merke rk(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 MovementAlgorit hm.

MovingObject has a method
SetMovementAlg orithm(Movement Algorithm* movementAlgorit hm)

if the body of this method reads
{
this->movementAlgori thm = movementAlgorit hm;
}

is this a memory leak every time a new MovementAlgorit hm 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->movementAlgori thm != NULL) {
delete this->movementAlgori thm;
}
this->movementAlgori thm = movementAlgorit hm;

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

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

Similar topics

14
3265
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; ++i){ if(i > (a_size/2)) return 0; //oops...ended before delete...is this a problem?
5
2262
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 the used memory only went down by 12 bytes. Any ideas on what else is being created or not cleaned up? Code ==> Sub Main() ' The following VB.NET code shows how memory is allocated and deallocated during object creation and destruction. ...
3
1980
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 bumping into doors. Specificly, Mozilla seems to be losing my... functions. Or variables. Except, I've tried alerts with dummy variables, and it seems to find THEM just fine... Does Mozilla start unloading existing memory right after a...
19
1745
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 querying to methods in a single static class, so whenever I need data, I pass a SQL string to a method and I am passed a datareader or else individual values (string, integer, etc). There is a horrible memory leak in this application. Just one...
13
422
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 Solaris/gcc, but crashes when run from VC++ (C mode). The problem occurs after the first true reallocation (second pass through main loop). The little debug part at the end of the loop prints one time, it crashes before a second is displayed. Seems...
7
2004
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 been freed. What would be the best way to do this? Is this kind of thing common practice? I would guess that perhaps a global long variable would be used, and malloc (free) would add (subtract) to this variable.
26
3067
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 read some of the items from the bottom up of the buffer, and some from the top down, moving the bottom items back to the new re-allocated bottom on every file read. Then when I've read all four files, I sort the top and bottom items separately...
34
2593
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? Contrary to some people that will start crying to that &@@""#~ programmer that wrote this sh!!!! you keep your cool and you do the following:
6
1881
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 similar to Richard Cornford's which are very easy to set up and watch run. <URL: http://groups.google.com/group/comp.lang.javascript/msg/e723d3324aaa4127> On my machine, O, S, and FF all level off at around 38MB of RAM while
0
9721
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9602
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10639
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10376
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7661
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6881
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5688
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.