C++ Tip – Being safe with Pointers

May 5th, 2010 by Tim Jones Leave a reply »

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;
 

Share and Enjoy:
  • Digg
  • del.icio.us
  • DZone
  • MisterWong
  • Reddit
  • StumbleUpon
  • Technorati
  • Slashdot
  • LinkedIn
  • MySpace
  • Yahoo! Buzz

Did you like this tutorial/blog post? Feel free to donate to keep more comin', and have more contests.

Advertisement

4 comments

  1. Alexander Alemayhu says:

    Thanks for the tip :)

  2. Maldoror says:

    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 :)

    • Tim Jones says:

      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.

  3. Jason Norris says:

    Very significant tips. I’ve troubleshooted a lot of code for people where the problem was accessing a NULL pointer.

Leave a Reply