Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Where to free memory?

Reply
Thread Tools

Where to free memory?

 
 
Phil
Guest
Posts: n/a
 
      11-09-2009
Hello all,
Let's say I have two classes A and B defined as follows:

// ClassA.h //////////////////////////
class ClassA
{
public:
void ClassA(int nItems); // constructor
virtual ~ClassA();
protected:
double *myTable; // My table of nItems double values
}
/////////////////////////////////////


// ClassA.cpp ///////////////////////
void ClassA(int nItems)
{
// Allocate memory for the table of double values
myTable=(double*)calloc(nItems, sizeof(double));
}

~ClassA()
{
// Should I free the memory allocated for myTable here?
// free(myTable);
// myTable=NULL;
}
/////////////////////////////////////


// ClassB.h //////////////////////////
#include "ClassA.h"
class ClassB
{
public:
void ClassB();
protected:
ClassA classA(int nItems);
}
/////////////////////////////////////


// ClassB.cpp ///////////////////////
void ClassB()
{
classA=new ClassA(10);
}
/////////////////////////////////////

My question is: when should I free the memory allocated for myTable
array of object classA ?
I am using MS Visual C++ 6.0 and Vista. Given the above code, I get a
memory leak. OK.
But if I free the memory as commented out in the destructor, I get an
error message pointing at the free(myTable) line
"memory check error at 0x02FDAA50 = 0xFE, should be 0xFD."
What is the correct way to free the memory ?
TIA,
Phil
 
Reply With Quote
 
 
 
 
Victor Bazarov
Guest
Posts: n/a
 
      11-09-2009
Phil wrote:
> Let's say I have two classes A and B defined as follows:
> [..shudder..]
>
> My question is: when should I free the memory allocated for myTable
> array of object classA ?


Please search the Web for, and read about, the "Rule of Three". Once
you comprehend what it is saying, drop dynamic memory management and
start using the standard containers like 'std::vector<double>'. You
will not have to "free memory" ever again.

> I am using MS Visual C++ 6.0 and Vista.


Get the latest free MS VC++ Express Edition and enjoy a much improved
compiler, a vastly better standard library, et cetera. Did I mention
it's free?

> [..]


V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
FREE 20 4x6 Digital Prints FREE 8x10 Print FREE Photo Website to Store and Share Photo's flashlarue Digital Photography 1 02-10-2006 11:47 PM



Advertisments