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
Always initialize pointers
//Check for a valid pointer!
if(MyLastPointer) {
std::cout << *MyLastPointer; //Good
}
Always free allocated memory
int* Y = new int;
X[0] = 0;
X[1] = 1;
X[2] = 2;
*Y = 3;
//End of program – BAD!
int* Y = new int;
X[0] = 0;
X[1] = 1;
X[2] = 2;
*Y = 3;
delete [] X; //Note the []
delete Y; //Note no []
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;
Did you like this tutorial/blog post? Feel free to donate to keep more comin', and have more contests.
Thanks for the tip
Hi, nice tips everyone should follow!
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
Thanks for the contributions! I didn’t know that deleting a NULL pointer was safe under the standard. Regarding your last tip though – that’s something definitely that needs to be done, and I am surprised I forgot to add it.
Very significant tips. I’ve troubleshooted a lot of code for people where the problem was accessing a NULL pointer.