"clinisbut" <clinis...@gmail.com> ha scritto nel messaggionews:869a5b8b-4b9b-4f6e-a53d-4adc8ecafa03@f3g2000hsg.googlegroups.com...
I have this object:
class ProtocolTPC
{
private:
unsigned char start[3];
unsigned char status1;
unsigned char status2;
unsigned char status3;
unsigned char psize;
unsigned char pnum[2];
unsigned char** data;
unsigned char crc[2];
~ProtocolTCP()
{
if( packet_number > 0 )
{
for( int i=0; i< packet_number; i++ )
{
delete this->data[i];
}
delete[] this->data;
}
VC debug says I'm having a memory leak of 3 vars and I think these are
the fixed arrays I have in my object.
Please stop using these raw C arrays.
I see no reason to use raw C arrays... you should use them only in very
particular cases (e.g. maybe in kernel driver development, you have no C++
STL available, so you must use C-like stuff).
Please use STL robust C++ container classes, like std::vector or
std::string, or MFC/ATL CString.
If you use a robust C++ container class, you can forget about delete, memory
leaks, and things like that.
You can just focus on your main algorithm, and not waste your time with
memory leak bugs, wrong destruction, buffer-overflows, etc.
For example, the above code becomes something like this:
#include <vector>
// I think unsigned char is BYTE for you...
// So I'm using BYTE, because I think BYTE is more readable and meaningful
// than "unsigned char", IMHO.
class ProtocolTPC
{
private:
std::vector< BYTE > start;
BYTE status1;
BYTE status2;
BYTE status3;
BYTE psize;
std::vector<BYTE> pnum;
unsigned char** data;
// 'data' is not clear to me... maybe it is a vector of vectors?
// If so, code like this:
std::vector< std::vector< BYTE > > data;
unsigned char crc[2];
std::vector< BYTE > crc;
In constructor, setup vectors initial sizes:
ProtocolTPC::ProtocolTPC()
{
// Set vector (initial) size
start.resize(3);
pnum.resize(2);
crc.resize(2);
// Other initialization...
}
In the destructor... you just do nothing :) because the vector instances are
automatically cleaned up by their own destructors.
No memory leak, no buffer overflows, no useless complex code... This is the
beauty of STL and C++ robust container classes.
Giovanni
STL (I heard of it sometimes, but no time to study it).
I will take a look at its use, it seams very easy to use.