473,769 Members | 5,900 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Memory Leak in this simple C++ program, a compiler bug ?

Hi,
I have this following simple c++ program, it will produce memory leak
( see what I did below ).
My observation also showed that:
There will be a mem leak when all the 3 conditions are true:
1. CallControlData does not provide a operator=
2. INUserHandle's operator= returns a object instead of a reference
3. Use CC -g main_leak.C instead of CC main_leak.C to compile.

You change any of the above condition, there will be NO mem leak.
The CC I used is Sun's /opt/SUNWspro/SC4.2/bin/CC.

If I use g++, and if all the above 3 conditions are true, there will be
memory leak. Besides that, even we
don't use g++ -g option, there will still be memory leak.

Can somebody explain this ?

Source of my main_leak.C is:
#include <iostream.h>
#define NULL 0
const int Size = 10;
short printlevel = 0;

class HandleBase
{
public:
int i;
};

class INUserHandle
{
public:
INUserHandle()
{
cout << "Entering INUserHandle()" << endl;
pchar = new char[Size];
impl = new HandleBase;
cout << "this = "<< this << endl;
cout << "Leaving INUserHandle()" << endl;
}
INUserHandle(co nst INUserHandle& handle)
:pchar ( NULL)
, impl( NULL )
{
cout << "Entering INUserHandle(co nstINUserHandle &)" << endl;
pchar = new char[Size];
impl = new HandleBase(*han dle.impl);
for ( int i = 0; i < Size ; i++ )
{
pchar[i] = handle.pchar[i];
}
cout << "this = "<< this << endl;
cout << "Leaving INUserHandle(co nstINUserHandle &)" << endl;
}

// Note here, that one is returning obj, one is returning reference.
//INUserHandle& operator=(const INUserHandle& handle)
INUserHandle operator=(const INUserHandle& handle)
{
cout << "Entering INUserHandle::o perator= "<< endl;
if( this != &handle ) {
delete [] pchar;
pchar = new char[Size];

delete impl;
impl = new HandleBase(*han dle.impl);
for ( int i = 0; i < Size ; i++ )
{
pchar[i] = handle.pchar[i];
}
}
cout << "Leaving INUserHandle::o perator= "<< endl;
return *this;
}

~INUserHandle()
{
cout << "Entering ~INUserHandle() ." << endl;
delete [] pchar ;
delete impl;
cout << "this = "<< this << endl;
cout << "Leaving ~INUserHandle() ." << endl;
}

public:
char *pchar;
HandleBase *impl;
};

class CallControlData {
public:
public:
INUserHandle handle;

};

class CallControlData _assignment {
public:

CallControlData _assignment& operator=(const
CallControlData _assignment& cdata_ass)
{
cout << "Entering CallControlData _assignment::op ertor= " <<
endl;
handle = cdata_ass.handl e;

cout << "Leaving CallControlData _assignment::op ertor= " <<
endl;
return *this;
}
public:
INUserHandle handle;

};
void f()
{
CallControlData cdata1;
CallControlData cdata2;
cdata1 = cdata2;

//CallControlData _assignment cdata_ass1;
//CallControlData _assignment cdata_ass2;
//cdata_ass1 = cdata_ass2;
};

void g()
{
f();
};

int
main()
{
g();
//while ( 1 ) {int i;};
return 1;
}



What I did:
1. compile it.
2. run dbx a.out
3. in dbx prompt, type check -memuse
4. in dbx prompt, type run

$>/opt/SUNWspro/SC4.2/bin/CC -g main_leak.C
$>
$>dbx a.out
The major new features of this release relative to 3.2 are:

o The Collector now supports MT applications (see `help collectormt')
o Runtime checking (RTC) is supported with fork/exec/attach (see `help
rtc attach' for details)
o RTC has an API for allocators (see `help rtc api')
o New command `regs' to print current value of registers (see `help regs')
o New command `showblock' to give details about heap block (see `help
showblock')
o Enhanced `pathmap' command (see `help pathmap')
o New dbxenv variable 'language_mode' (see `help dbxenv' under
`language_mode' )
o New dbxenv variable 'output_inherit ed_members' (ee `help dbxenv' under
`output_inherit ed_members')
o Two new dbx read-only variables: $helpfile and $helpfile_html (see `help
help')
o New -v (verbose) flag to the `module' and `modules' commands
(see `help module' and `help modules')
o New +r flag to print and display commands (see `help print')
o Default value of dbxenv variable `scope_look_asi de' has been changed
to on (see `help dbxenv' under scope_look_asid e and `help scope')
o New `inobject' event for support of `stop inobject <c++_obj_exp> '
(see `help c++ inobject' and `help event specification')
o `inclass' event now supports template classes (see `help c++ inclass' and
`help event specification')
o `stop at <lineno>' now supports C++ template definitions as well as
C++ inlined functions defined in header files (see `help event
specification'
under `at' event)
o Support for new C++ operators: `const_cast', `dynamic_cast',
`reinterpret_ca st', and `static_cast'
o Support for new C++ `typeid' operator
o An HTML version of the help file is available (see `help help')

See also `help changes32'
The major new features of 3.2 (SPARCWorks 3.1) relative to 3.1 are:

o Objective C support (see `help ObjC')
o Fortran 90 support (see `help fortran')
o Runtime checking (RTC) gives information about memory usage
Reading symbolic information for a.out
Reading symbolic information for rtld /usr/lib/ld.so.1
Reading symbolic information for libm.so.1
Reading symbolic information for libC.so.5
Reading symbolic information for libw.so.1
Reading symbolic information for libc.so.1
Reading symbolic information for libdl.so.1
Reading symbolic information for libc_psr.so.1
(dbx)
(dbx)
(dbx) check -memuse
memuse checking - ON
(dbx) run
Running: a.out
(process id 21043)
Reading symbolic information for librtc.so
Skipping libm.so.1, already read
Skipping libC.so.5, already read
Skipping libw.so.1, already read
Skipping libc.so.1, already read
Skipping libdl.so.1, already read
Skipping libc_psr.so.1, already read
Enabling Error Checking... done
Entering INUserHandle()
this = 0xeffff314
Leaving INUserHandle()
Entering INUserHandle()
this = 0xeffff30c
Leaving INUserHandle()
Entering INUserHandle::o perator=
Leaving INUserHandle::o perator=
Entering INUserHandle(co nstINUserHandle &)
this = 0xeffff29c
Leaving INUserHandle(co nstINUserHandle &)
Entering ~INUserHandle() .
this = 0xeffff30c
Leaving ~INUserHandle() .
Entering ~INUserHandle() .
this = 0xeffff314
Leaving ~INUserHandle() .
Checking for memory leaks...

Actual leaks report (actual leaks: 2 total size: 14 bytes)

Total Num of Leaked Allocation call stack
Size Blocks Block
Address
====== ====== ========== =============== =============== =========
10 1 0x22848 operator new < INUserHandle::I NUserHandle <
INUserHandle::o perator = < CallControlData ::operator = < f < g < main
4 1 0x23238 operator new < INUserHandle::I NUserHandle <
INUserHandle::o perator = < CallControlData ::operator = < f < g < main
Possible leaks report (possible leaks: 0 total size: 0 bytes)
Checking for memory use...

Blocks in use report (blocks in use: 0 total size: 0 bytes)

execution completed, exit code is 1
(dbx) quit
$>
Jul 22 '05 #1
6 2566
Scott Niu wrote:
Hi,
I have this following simple c++ program, it will produce memory leak
( see what I did below ).
My observation also showed that:
There will be a mem leak when all the 3 conditions are true:
1. CallControlData does not provide a operator=
2. INUserHandle's operator= returns a object instead of a reference
3. Use CC -g main_leak.C instead of CC main_leak.C to compile.


Hi Scott,

I didn't get into the details of your program. But I can say that
operator = must return a reference. Concerning the different
compiler flags, the reason might be that without -g dbx just does
not detect the memory leak. But the details of this are offtopic
here as memory leak detection is certainly not defined in the
standard. You might want to refer to Sun's CC Forum concerning
this. I don't know which version of Sun's C++ compiler you are
using, but it seems to me to be an obsolete one. So upgrading might
be an option...
Cheers,

Tom
Jul 22 '05 #2
Scott Niu wrote:
Hi,
I have this following simple c++ program, it will produce memory leak
( see what I did below ).
My observation also showed that:
There will be a mem leak when all the 3 conditions are true:
1. CallControlData does not provide a operator=
2. INUserHandle's operator= returns a object instead of a reference
3. Use CC -g main_leak.C instead of CC main_leak.C to compile.


Hi Scott,

I didn't get into the details of your program. But I can say that
operator = must return a reference. Concerning the different
compiler flags, the reason might be that without -g dbx just does
not detect the memory leak. But the details of this are offtopic
here as memory leak detection is certainly not defined in the
standard. You might want to refer to Sun's CC Forum concerning
this. I don't know which version of Sun's C++ compiler you are
using, but it seems to me to be an obsolete one. So upgrading might
be an option...
Cheers,

Tom
Jul 22 '05 #3
"Scott Niu" <sc****@qd.luce nt.com> wrote:
Hi,
I have this following simple c++ program, it will produce memory leak

#include <iostream.h>
Error, nonstandard header
#define NULL 0
Error, redefinition of NULL

Change those 2 lines to:
#include <iostream>
using namespace std;
void f()
{ [snip] };
Syntax error - extra semicolon
void g()
{
f();
};


Same again

Fix those problems and then see if you still get the problem.
Could it be that this 'dbx' program is just being paranoid?

NB. If you are more interested in solving your problem than
in finding out what happened, modify your code to use
automatic memory management (eg. use std::string for pchar
and std::auto_ptr for impl).

Also, your objects are not exception-safe.
Jul 22 '05 #4
On 8 Nov 2004 12:35:14 -0800, ol*****@inspire .net.nz (Old Wolf) wrote:
"Scott Niu" <sc****@qd.luce nt.com> wrote:
void f()
{

[snip]
};


Syntax error - extra semicolon


That's not a syntax error. While it's technically against style for
putting in blank or no-op statements in C++, it compiles correctly.
Jul 22 '05 #5
"Scott Niu" <sc****@qd.luce nt.com> wrote in message news:<cm******* *@netnews.proxy .lucent.com>...
I have this following simple c++ program, it will produce memory leak
( see what I did below ). [snip] Can somebody explain this ?

Source of my main_leak.C is: [snips] class CallControlData {
public:
public:
INUserHandle handle;

}; [snips] CallControlData cdata1;
CallControlData cdata2;
cdata1 = cdata2;

//CallControlData _assignment cdata_ass1;
//CallControlData _assignment cdata_ass2;
//cdata_ass1 = cdata_ass2;
};

[snipper]

Note that the class CallControlData does not have an explicit op=
in it. So it will do the default shallow copy. But class INUserHandle
has a call to new in it. So, yes, this is a mem leak.

The class CallControlData _assignment has an op= in it, but I never
checked if it does the correct thing.
Socks
Jul 22 '05 #6
bk***@ncf.ca (Raymond Martineau) wrote in message news:<9m******* *************** **********@4ax. com>...
On 8 Nov 2004 12:35:14 -0800, ol*****@inspire .net.nz (Old Wolf) wrote:
"Scott Niu" <sc****@qd.luce nt.com> wrote:
void f()
{ [snip] };
Syntax error - extra semicolon


That's not a syntax error. While it's technically against
style for putting in blank or no-op statements in C++,


You can't have statements at file scope, only declarations
and definitions.

it compiles correctly.


// file: r.cc
void f() {};

$ g++ -o r r.cc -ansi -pedantic -W -Wall
r.cc:2: error: extra `;'
Jul 22 '05 #7

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

Similar topics

2
3648
by: Elbert Lev | last post by:
#When I'm running this script on my windows NT4.0 box, #every time dialog box is reopened there is memory growth 384K. #Bellow is the text I sent to Stephen Ferg (author of easygui) # I have tested the pure Tkinter, # by modifiing on of the examples in the distribution. # This little guy also exibits the same behaviour. # Namely: every time the window is closed and reoppend, # there is memory leak of several hundreds 384K
14
3264
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
4867
by: blugus | last post by:
Hi Guys, I've been try to use Dinkum STL library. It workes well first, but report memory leak in MFC Debug Mode. I use Dinkum Unabridged Library for VC++ V4.02, MSVC6, WIN2000 SERVER. I made a dialog based program by MSVC6, inserted simple code to use Dinkum STL Library, and added simple code like this.
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...
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();
8
8322
by: vidya.bhagwath | last post by:
Hello Experts, I am using std::string object as a member variable in one of the my class. The same class member function operates on the std::string object and it appends some string to that object. My sample code is as follows. ..h file content---------- #include <stdio.h>
17
2547
by: Mike | last post by:
Hello, I have following existing code. And there is memory leak. Anyone know how to get ride of it? function foo has been used in thousands places, the signature is not allowed to change. Thanks in advance,
20
1817
by: gNash | last post by:
Hi all, void main() { char *fp; fp=malloc(26); strcpy(fp,"ABCDEFGHIJKLMNOPQRSTUVWXYZ"); fp='\0'; free(fp); }
16
5104
by: graham.keellings | last post by:
hi, I'm looking for an open source memory pool. It's for use on an embedded system, if that makes any difference. Something with garbage collection/defragmentation would be nice. It should have the ability to allocate different size chunks of memory not just a single size. It should error check for double free, etc. And it should be usable by a mixture of C and C++ subsystems. If I get that, I'm happy. Thank you very much.
0
9586
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
9423
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
10210
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
8869
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
7406
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
6672
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
5298
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...
1
3956
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
2
3561
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.