Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

long-term test ¦ out of memory ¦ return array 1

Status
Not open for further replies.

moknine

Programmer
Dec 3, 2002
2
DE
Hi,
i am testing the function generateSp() which returns an array. The following code works. But when i run the prog for a long time (hours) i observe an incrementation of the used memory this ends with an "out of memory" :-(
What could be wrong in my code ?

#######################################
#include <iostream>

#define SP_SIZE 100

class CSp
{
public:
CSp();
~CSp();
CSp& operator=(const CSp &);
private:
double * const p;
};

CSp::CSp(): p(new double[SP_SIZE])
{
cout << &quot;const:&quot; << p << endl;
}

CSp::~CSp()
{
cout << &quot;destr:&quot; << p << endl;
delete []p;
}


CSp & CSp::eek:perator=(const CSp& right)
{
cout << &quot;assignment operator begin&quot; << endl;

for(int i = 0 ; i < SP_SIZE; i++ )
{
p = right.p;
}
return *this;
};

CSp generateSp()
{
cout << &quot;generateSp&quot; << endl;
CSp * p_spLocal = new CSp;
cout << &quot;generated Local CSp&quot; << endl ;
return * p_spLocal;
};

int main()
{
cout << &quot;prog start&quot; << endl;
while(1)
{
CSp spA;
cout << &quot;generated spA&quot; << endl;
spA = generateSp();
cout << &quot;generateSp, assigned it to A&quot; << endl;
}
return 0;
}
 
The reason of 'out of memory' is that you keep on creating new objects, thus allocating memory without freeing it.
In your function generateSp the locally created object of type CSp is returned, but never deleted.
To make this work properly do something like:

CSp generateSp()
{
cout << &quot;generateSp&quot; << endl;
CSp localObject
cout << &quot;generated Local CSp&quot; << endl ;
return p_spLocal; // returns object, then deletes it
};

If this doesn't work, try to implement an copy constructor instead of overloading the assignment operator.

And there's another bug in the assignment operator of CSp. Here is the fix:

CSp & CSp::eek:perator=(const CSp& right)
{
cout << &quot;assignment operator begin&quot; << endl;

for(int i = 0 ; i < SP_SIZE; i++ )
{
//HERE!
p = right.p;
}
return *this;
};

This copies the actual content of right's double array.

Hope this helps,
Tobi

 
strange, somehow this forum eats the square brackets... ;)
 
Always surround code pieces with
Code:
 and
or uncheck the box saying &quot;Process TGML&quot;. //Daniel
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top