John wrote:
> 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?
That depends on what the class does. If it allocates any resources, it
should have a destructor that deallocates them.
> (2).If in my code I only use "new" to declare new object, and do not
> use "delete", will it cause memory leak?
Yes. Everything you got from new should be deleted as soon as you don't
need it anymore.
> For example, in the following code:
>
> void class1::function1()
> {
> 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?
If you don't delete them, yes. However, since the pointers are local
variables within your function and not member variables of your class,
you don't need a destructor for cleaning them up, but rather would
delete them in the function. Do you actually need them to be pointers
anyway? If a direct instance suffices, use it.
> The two pointers, r1 and r2, and array rr[] are local variables, when
> the code exits function1(), these local variables should be released
> automatically.
The local variables are, but not the objects they point to.
> Am I right?
What you wrote is right, but I don't think it's what you meant