Arguably no other area of C++ confuses more people and causes more frustration than pointers. Here's a few quick tips to keep safe while using them.
Always check pointers
void MyFunc(int* X) {
std::cout << *X; //Bad!
}
void MyFunc(int* X) {
if(!X) return; //Better
std::cout << *X;
}
Always initialize pointers
int* MyPointer; //Bad!
std::cout << *MyPointer; //Potential Boom!
int* MyOtherPointer = NULL; // or, = 0
std::cout << *MyOtherPointer; //Still not good
int* MyLastPointer = NULL;
//Check for a valid pointer!
if(MyLastPointer) {
std::cout << *MyLastPointer; //Good
}
Always free allocated memory
int* X = new int[3];
int* Y = new int;
X[0] = 0;
X[1] = 1;
X[2] = 2;
*Y = 3;
//End of program - BAD!
int* X = new int[3];
int* Y = new int;
X[0] = 0;
X[1] = 1;
X[2] = 2;
*Y = 3;
delete [] X; //Note the []
delete Y; //Note no []
//Even better
int* X = new int[3];
int* Y = new int;
if(X) {
X[0] = 0;
X[1] = 1;
X[2] = 2;
}
if(Y) {
*Y = 3;
}
if(X) delete [] X;
if(Y) delete Y;
Thumbs up!.
Email (required, not published):
Website:
Email (required, not published):
Website:
One advice regarding your last hint:
int* X = new int[3];
if(X) {...}
If the 'new' will fail a 'bad_alloc' exception will be thrown. Only in the early days of C++ the value NULL was the return value of a failed 'new'. (but some compiler will still return NULL - I am not sure...)
And the c++ standard says it is safe to delete a NULL pointer. So, it is obsolete to ask if the object exists before you destroy it:
if(Y) // 'IF' is not needed
delete Y;
If Y is not NULL and Y is not the memory you allocated you are in trouble anyway ;)
Also - in addition to your tipps: A good style is to set a pointer variable to NULL immediately after you destroyed the object. So, no trouble in other functions when you use the variable (mostly a dynamically created member of a class) and your check for NULL work...
delete Y;
Y = NULL;
Greetings,
~Maldoror
ps: I hope you understand my English - it's not my mother language :)
Email (required, not published):
Website:
Email (required, not published):
Website:
Email (required, not published):
Website:
Email (required, not published):
Website: