473,757 Members | 8,356 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Memory leak

Hi all:

When I run my code, I find that the memory that the code uses keeps
increasing.
I have a PC with 2G RAM running Debian linux. The code consumes 1.5G
memory by the time it finishes execution. But I do not think it needs
so much memory. About 500M memory should be enough. I have following
questions about memory leak.
(1).If in my code I only define constructor for my class, and do not
define destructor, will it cause memory leak?
(2).If in my code I only use "new" to declare new object, and do not
use "delete", will it cause memory leak?

For example, in the following code:

void class1::functio n1()
{
class2 *r1;
class2 *r2 = new class2;
class2 *rr[20];

......

function2(rr);

......
//r1 and r2 are also used in function1().

}

In the above code, I have two classes and I define constructor for the
two classes and do not define destructor. In function1(), I declare
two pointers of class2 and an array of pointer of class2. The array rr
is used to bring back values from function2(). For r2, I do not use
"delete".
Will r1, r2 and the array rr[] cause memory leak?
The two pointers, r1 and r2, and array rr[] are local variables, when
the code exits function1(), these local variables should be released
automatically.
Am I right?

Thanks a lot.

John
Jul 22 '05
32 3859
John wrote:
Hi Karl:
Thank you very much. I understand now.
On this discussion list, there are so many warm-hearted experts who
spend their precious time instructing me--a newbie of C++.
I have two questions. Is the following code free of trouble?
void f()
{
X *x0 = new X(10);//create and initialize an object of class X.
X *x1;
x1 = x0;
delete x1; //release the memory that x0 uses.
}

I do not "delete" x0, but "delete" x1 to release the memory. Will it
cause any problem. An old code that I am modifying uses this approach.
No problems there. Although it isn't a particularly "safe" way to do
things, because code that is using x0 doesn't necessarily know that the
memory to which it points has been deleted.

If you need to use multiple pointers to point to the same dynamic
memory, try to come up with some scheme that let's you know which
pointer "owns" (i.e., is responsible for deleting) the memory. One
possible approach is as follows:

---
X *x0 = new X(10); // Allocate some memory. This memory is owned by x0.
X *x1 = NULL; // This pointer doesn't own anything, so it is NULL.

f(x0); // Do something with x0.

x1 = x0; // Transfer ownership of memory
x0 = NULL; // to x1.

f(x1); // Do something with x1.

if (x1) delete x1; // Delete the memory, but if and only if x1 owns it.
---
I'd mostly try to just avoid passing ownership of allocated memory
blocks around in the first place, though. Also, depending on what you
are doing, you may try using an auto_ptr to "own" your allocated memory,
so that you don't need to worry about whether or not it gets
deallocated. For example:

void f()
{
auto_ptr<X> x0 = new X(10);
auto_ptr<X> x1;

// Do something with x0.

x1 = x0 ;

// Do something with x1.

} // Ignore the memory, it will get deleted on its own.
A nice auto_ptr tutorial is available here:
http://www.gotw.ca/publications/usin...ffectively.htm

Another question is:
What is the differece between the two lines below:
X *xx = new X;//line 1
X *xx1;//line 2
Line 1 declare xx and allocate it memory.
Line 2 declare xx1 and xx1 points to somewhere unknown. Has xx1 been
allocated memory?
This would all depend on the platform and/or implementation, but for the
sake of discussion, let's say that pointers, on your system, require 4
bytes, and the object you are calling X requires 32 bytes.

Let's look at line 2 first. This allocates 4 bytes of "automatic"
memory. By automatic, we mean that the any allocation and deallocation
of the memory is handled for us by the compiler. This is no different
from declaring an int, double, char, etc. The standard doesn't specify
how this must be implemented, but typically this occurs on what is
referred to as "the stack". What is the value contained in those 4
bytes? We can't really say, because it wasn't initialized.

Now, line 1. Obviously this line must do at least as much as line 2. It
allocates 4 bytes (which happen to have the name xx) of automatic
memory. It also allocates 32 bytes (at least) of dynamic memory.
Dynamic memory means that the programmer is responsible for allocating
and deallocating it, instead of the compiler. In most implementations ,
this memory comes from a place called "the heap" or "the free store"
(refer to other posts in this newsgroup for arguments about what to call
this). What is in the 4 bytes called xx? If we look, we should find
that the value there is the memory address at which our 32 byte block
got allocated, which is, of course, why we call it a pointer.
Thanks a lot.

John


Alan
Jul 22 '05 #21
John posted:
void f()
{
X *x0 = new X(10);//create and initialize an object of class X.
X *x1;
x1 = x0;
delete x1; //release the memory that x0 uses.
}

I do not "delete" x0, but "delete" x1 to release the memory. Will it
cause any problem. An old code that I am modifying uses this approach.

Another question is:
What is the differece between the two lines below:
X *xx = new X;//line 1
X *xx1;//line 2
Line 1 declare xx and allocate it memory.
Line 2 declare xx1 and xx1 points to somewhere unknown. Has xx1 been
allocated memory?

The very reason that you ask this question shows that you don't understand
pointer variables. I'll try enlighten you:

int DogAge;
DogAge = 4;

I have declared a variable DogAge . To declare a variable, you need
specify two and only two pieces of information: 1) The type, 2) The token-
name.
In the preceeding example, the type is int and the token-name is DogAge .
Essentially what you're doing when declaring a variable is just allocating a
piece of memory. How much memory is allocated for each variable? This is
determined from the type you specify. For example, for int , it might be
16 Bits. And there you have it: When you write

int DogAge;

you are allocating 16 Bits of memory. The type of the variable also tells
something else, it determines how the variable is *treated*, ie. in what way
is a value represented in those 16 Bits. Here's a few declarations, with a
type and a token-name:

int k;
char t;
double r;
int* s;
char* q;
Here's the part that you don't understand yet:

int* s;

Here, the type is int* and the token-name is s . I am allocating a piece
of memory, the size of which is determined by the type. Let's say that the
size of an int* is 32 Bits. So now, I have allocated 32 Bits of memory,
plain and simple. As I've said, the type name also specifies in what way a
variable is treated and hence what way a value is represented in memory
using those bits. Take the following:

int* s;

s = 4567;
Do you see what I'm getting at? A pointer variable is just like any other
variable. You store a value in it. It just so happens that the value you
store in a pointer variable is a memory address. If you understand this,
then you'll understand that all pointer variables allocate the *same* amount
of memory:

char* k;
double* p;
int* t;

----

Hoping that that has helped, let's look at your code:
void f()
{
X *x0 = new X(10); //I'm going to split this line
//into 2 lines for clarity

X* x0; //Here you have declared a varible

x0 = new X(10); //Here you have copied a value into the
//variable. The value is the memory address
//of the memory allocated by "new"

//"new" is like a function that returns
//the address of the memory allocated
X *x1; //Here you have declared a variable

x1 = x0; //You have copied the value stored in the variable
// x0 into the variable x1

//At this point, x0 and x1 contain the same value
// delete is like a function that takes a memory address
//as a paramter. It wants the memory address of memory
//previously allocated using "new".
//I have a question for you here now. A little test. Would
//there be a difference at this point in writing

delete x1;

//as opposed to writing

delete x0;

//?
}
Hope that helps
-JKop
Jul 22 '05 #22

I anticipate that you may wonder about the difference, if any, between:
int* pNumber;

int *pNumber;
Look at the following:

GetSquareRoot(5 6);

can be written as
GetSquareRoot(5 0 + 6);

GetSquareRoot(5 0 +6);

GetSquareRoot(5 0+ 6);

GetSquareRoot(5 0+6);
You can stick in spaces anywhere you want with C++. You can even write a
program all on one line:
int main(void) { int j; j = 4; GetSquareRoot(j ); return 0; }

int main(void){intj ;j=4;GetSquareR oot(j);return0; }
So, in summation:
int* s;
int *s;
will compile exactly the same. But...
int *s is extremely stupid. This implies that the type of the variable is
int . It's not. The type of the variable is int* , and the name of the
variable is simply s . So always keep the asterisk beside the TYPE!!!
-JKop

Jul 22 '05 #23
JKop wrote:

int *s is extremely stupid. This implies that the type of the variable is
int . It's not. The type of the variable is int* , and the name of the
variable is simply s . So always keep the asterisk beside the TYPE!!!
-JKop


int* s isn't so great either. Consider:

int* s, t, u, v;
What did I just create? It wasn't four variable of type (int*). I
created s of type (int*), and t, u, and v of type (int).

The proper way to do this is (ignoring whitespace styles):

int *s, *t, *u, *v;

Or, you might argue that it would be more proper to use:

int* s;
int* t;
int* u;
int* v;

Really, I prefer not to take sides on the debate, and just say, whatever
you do, do it consistently!

Alan
Jul 22 '05 #24
JKop <NU**@NULL.NULL > wrote in message news:<r5******* ***********@new s.indigo.ie>...
John posted:
void f()
{
X *x0 = new X(10);//create and initialize an object of class X.
X *x1;
x1 = x0;
delete x1; //release the memory that x0 uses.
}

I do not "delete" x0, but "delete" x1 to release the memory. Will it
cause any problem. An old code that I am modifying uses this approach.

Another question is:
What is the differece between the two lines below:
X *xx = new X;//line 1
X *xx1;//line 2
Line 1 declare xx and allocate it memory.
Line 2 declare xx1 and xx1 points to somewhere unknown. Has xx1 been
allocated memory?

The very reason that you ask this question shows that you don't understand
pointer variables. I'll try enlighten you:

int DogAge;
DogAge = 4;

I have declared a variable DogAge . To declare a variable, you need
specify two and only two pieces of information: 1) The type, 2) The token-
name.
In the preceeding example, the type is int and the token-name is DogAge .
Essentially what you're doing when declaring a variable is just allocating a
piece of memory. How much memory is allocated for each variable? This is
determined from the type you specify. For example, for int , it might be
16 Bits. And there you have it: When you write

int DogAge;

you are allocating 16 Bits of memory. The type of the variable also tells
something else, it determines how the variable is *treated*, ie. in what way
is a value represented in those 16 Bits. Here's a few declarations, with a
type and a token-name:

int k;
char t;
double r;
int* s;
char* q;
Here's the part that you don't understand yet:

int* s;

Here, the type is int* and the token-name is s . I am allocating a piece
of memory, the size of which is determined by the type. Let's say that the
size of an int* is 32 Bits. So now, I have allocated 32 Bits of memory,
plain and simple. As I've said, the type name also specifies in what way a
variable is treated and hence what way a value is represented in memory
using those bits. Take the following:

int* s;

s = 4567;
Do you see what I'm getting at? A pointer variable is just like any other
variable. You store a value in it. It just so happens that the value you
store in a pointer variable is a memory address. If you understand this,
then you'll understand that all pointer variables allocate the *same* amount
of memory:

char* k;
double* p;
int* t;

----

Hoping that that has helped, let's look at your code:
void f()
{
X *x0 = new X(10); //I'm going to split this line
//into 2 lines for clarity

X* x0; //Here you have declared a varible

x0 = new X(10); //Here you have copied a value into the
//variable. The value is the memory address
//of the memory allocated by "new"

//"new" is like a function that returns
//the address of the memory allocated
X *x1; //Here you have declared a variable

x1 = x0; //You have copied the value stored in the variable
// x0 into the variable x1

//At this point, x0 and x1 contain the same value
// delete is like a function that takes a memory address
//as a paramter. It wants the memory address of memory
//previously allocated using "new".
//I have a question for you here now. A little test. Would
//there be a difference at this point in writing

delete x1;

//as opposed to writing

delete x0;

//?
}


Thanks a lot!
Now I take the test.-:)
Both "delete x1" and "delete x0" release the same memory. But "delete
x1" causes "dangling problem" to x0; "delete x0" causes "dangling
problem" to x1.
Am I right?
By the way, what is the difference between "int* s" and "int *s". My
text book uses "int *s".

Thanks again.

John
Jul 22 '05 #25
JKop <NU**@NULL.NULL > wrote in message news:<tc******* ***********@new s.indigo.ie>...
I anticipate that you may wonder about the difference, if any, between:
int* pNumber;

int *pNumber;


Exactly! I post a follow-up to your last post asking this question. I
am clear now. Thanks.

John
Jul 22 '05 #26
Hi Alan:

Thank you very much for the instruction!

John

Alan Johnson <al****@mailand news.com> wrote in message news:<40******* *@news.ua.edu>. ..
John wrote:
Hi Karl:
Thank you very much. I understand now.
On this discussion list, there are so many warm-hearted experts who
spend their precious time instructing me--a newbie of C++.
I have two questions. Is the following code free of trouble?
void f()
{
X *x0 = new X(10);//create and initialize an object of class X.
X *x1;
x1 = x0;
delete x1; //release the memory that x0 uses.
}

I do not "delete" x0, but "delete" x1 to release the memory. Will it
cause any problem. An old code that I am modifying uses this approach.


No problems there. Although it isn't a particularly "safe" way to do
things, because code that is using x0 doesn't necessarily know that the
memory to which it points has been deleted.

If you need to use multiple pointers to point to the same dynamic
memory, try to come up with some scheme that let's you know which
pointer "owns" (i.e., is responsible for deleting) the memory. One
possible approach is as follows:

---
X *x0 = new X(10); // Allocate some memory. This memory is owned by x0.
X *x1 = NULL; // This pointer doesn't own anything, so it is NULL.

f(x0); // Do something with x0.

x1 = x0; // Transfer ownership of memory
x0 = NULL; // to x1.

f(x1); // Do something with x1.

if (x1) delete x1; // Delete the memory, but if and only if x1 owns it.
---
I'd mostly try to just avoid passing ownership of allocated memory
blocks around in the first place, though. Also, depending on what you
are doing, you may try using an auto_ptr to "own" your allocated memory,
so that you don't need to worry about whether or not it gets
deallocated. For example:

void f()
{
auto_ptr<X> x0 = new X(10);
auto_ptr<X> x1;

// Do something with x0.

x1 = x0 ;

// Do something with x1.

} // Ignore the memory, it will get deleted on its own.
A nice auto_ptr tutorial is available here:
http://www.gotw.ca/publications/usin...ffectively.htm

Another question is:
What is the differece between the two lines below:
X *xx = new X;//line 1
X *xx1;//line 2
Line 1 declare xx and allocate it memory.
Line 2 declare xx1 and xx1 points to somewhere unknown. Has xx1 been
allocated memory?


This would all depend on the platform and/or implementation, but for the
sake of discussion, let's say that pointers, on your system, require 4
bytes, and the object you are calling X requires 32 bytes.

Let's look at line 2 first. This allocates 4 bytes of "automatic"
memory. By automatic, we mean that the any allocation and deallocation
of the memory is handled for us by the compiler. This is no different
from declaring an int, double, char, etc. The standard doesn't specify
how this must be implemented, but typically this occurs on what is
referred to as "the stack". What is the value contained in those 4
bytes? We can't really say, because it wasn't initialized.

Now, line 1. Obviously this line must do at least as much as line 2. It
allocates 4 bytes (which happen to have the name xx) of automatic
memory. It also allocates 32 bytes (at least) of dynamic memory.
Dynamic memory means that the programmer is responsible for allocating
and deallocating it, instead of the compiler. In most implementations ,
this memory comes from a place called "the heap" or "the free store"
(refer to other posts in this newsgroup for arguments about what to call
this). What is in the 4 bytes called xx? If we look, we should find
that the value there is the memory address at which our 32 byte block
got allocated, which is, of course, why we call it a pointer.
Thanks a lot.

John


Alan

Jul 22 '05 #27
John posted:
Both "delete x1" and "delete x0" release the same memory. But "delete
x1" causes "dangling problem" to x0; "delete x0" causes "dangling
problem" to x1.

It's my opinion that people in the know-how about programming tend to
undermine the intelligence, ingenuity, and creativity of the human mind.
Let's say for example we *do* call:
delete x1;
And as you've said, we have a "dangling problem". I myself am an intelligent
person, I know what's going on in my code, and thus, nothing less than a
brain hemerage would make me fiddle with the memory again after I've freed
it. You'll see that some people may do the following:

delete x1;

x0 = 0;
I myself find this degrading. I'm not sufficently stupid to go messing with
x0 afterwards.

In summation:

I don't recognize or acknowledge "a dangling pointer" as a problem. That's
just my opinion on the subject.
-JKop

Jul 22 '05 #28
Alan Johnson posted:

int* s isn't so great either. Consider:

int* s, t, u, v;
What did I just create? It wasn't four variable of type (int*). I
created s of type (int*), and t, u, and v of type (int).
When I was first enlightened long ago that this statement declares s as
type int* and t u v as type int , I was disgusted. Not much point
talking about it though, that's just how it is. C++ is due for an overhall!


The proper way to do this is (ignoring whitespace styles):

int *s, *t, *u, *v;
The only reason I don't like this is that it suggests:

Type = int
Token-name = *s

Or, you might argue that it would be more proper to use:

int* s;
int* t;
int* u;
int* v;
....it's too beautiful

Really, I prefer not to take sides on the debate, and just say,
whatever
you do, do it consistently!


Although it *would* be more fun to hold a gun to everyone's head and tell
them to do the following:

int* s;
int* t;
int* u;
int* v;
-JKop
Jul 22 '05 #29
> Thanks a lot!
Now I take the test.-:)
Both "delete x1" and "delete x0" release the same memory. But "delete
x1" causes "dangling problem" to x0; "delete x0" causes "dangling
problem" to x1.
Am I right?
By the way, what is the difference between "int* s" and "int *s". My
text book uses "int *s".

Thanks again.

John


It's the same thing. I prefer int* s;

Anil Mamede
Jul 22 '05 #30

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

Similar topics

8
3413
by: ranjeet.gupta | last post by:
Dear All Is the Root Cause of the Memory corruption is the Memory leak, ?? suppose If in the code there is Memory leak, Do this may lead to the Memory Corruption while executing the program ? In nut shell, what is/are the realtion/s between the Memory Leak and Memory Corruption. Juts Theoritical Assumtion below:
17
4814
by: José Joye | last post by:
Hi, I have implemented a Service that is responsible for getting messages from a MS MQ located on a remote machine. I'm getting memory leak from time to time (???). In some situation, it is easier to reproduce (e.g.: remote machine not available). After about 1 day, I get a usage of 300MB of memory. I have used .NET Memory Profiler tool to try to see where the leak is located. For all the leaky instances, I can see the following (I...
4
6093
by: Don Nell | last post by:
Hello Why is there a memory leak when this code is executed. for(;;) { ManagementScope scope = new ManagementScope(); scope.Options.Username="username"; scope.Options.Password="password"; scope.Path.Path=@"\\pc\root\cimv2";
20
8119
by: jeevankodali | last post by:
Hi I have an .Net application which processes thousands of Xml nodes each day and for each node I am using around 30-40 Regex matches to see if they satisfy some conditions are not. These Regex matches are called within a loop (like if or for). E.g. for(int i = 0; i < 10; i++) { Regex r = new Regex();
23
4566
by: James | last post by:
The following code will create memory leaks!!! using System; using System.Diagnostics; using System.Data; using System.Data.SqlClient; namespace MemoryLeak
8
8552
by: Adrian | last post by:
Hi I have a JS program that runs localy (under IE6 only) on a PC but it has a memory leak (probably the known MS one!) What applications are there that I could use to look at the memory usage of each object within my JS app to help locate my problem? Thanks
7
6935
by: Salvador | last post by:
Hi, I am using WMI to gather information about different computers (using win2K and win 2K3), checking common classes and also WMI load balance. My application runs every 1 minute and reports the status of the machines. Upon we follow the .NET object lifetime recommendations the application is constantly consuming more memory! The problem is on the ManagementObjectSearch, upon we Dispose the object it seems that is not releasing the...
3
5326
by: Jim Land | last post by:
Jack Slocum claims here http://www.jackslocum.com/yui/2006/10/02/3-easy-steps-to-avoid-javascript- memory-leaks/ that "almost every site you visit that uses JavaScript is leaking memory". Anybody know anything about this? Does *Javascript* leak memeory, or does the *browser* leak memory?
7
15715
by: Ragnar Agustsson | last post by:
Hi all I have been wandering about the best way to sandbox memory leaks in 3rd party libraries when using them from the .Net framework. I have a 3rd party library, written in C++, that leaks a lot of memory but I still had to use it. 1. After using DLLImport and seeing the memory leak I tried to load and
22
9361
by: Peter | last post by:
I am using VS2008. I have a Windows Service application which creates Crystal Reports. This is a multi theaded application which can run several reports at one time. My problem - there is a memory leak someplace. I can not detect the memory leak by running several reports by hand, but when I run tha app as a servrice and process few hundred reports there is significant memory leak. The application can consume over 1GB of memory where it...
0
9489
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
9298
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
10072
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...
1
9885
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9737
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8737
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7286
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...
1
3829
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3399
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.