CPP Dangerous Pointers Handling

Memory Leaks and Stray Pointers.

  • One of the most serious issues and complaints about pointers is Memory leaks.
  • If you reassigning your pointer before deleting the memory to which it points you got Memory leaks.
    unsigned  int * pNumber = new unsigned int;
    *pNumber = 32;
    pNumber = new unsigned int;  // You must free up the memory before this
    *pNumber = 45;
    // The result of this is that we have allocated 
    // memory on the free store with the 1. statement
    // that we never can reach again;

Stray, Wild, or Dangling Pointers.

  • Errors you create in your programs with pointers can be among the most difficult to find and among the most problematic.
  • One source of bugs that are especially nasty and difficult to find in C++ is stray (also called a wild or dangling pointer) pointers.
  • A stray pointer is created when you call delete on a pointer— thereby freeing the memory that it points to— and then you don't set it to null.
  • If you then try to use that pointer again without reassigning it, the result is unpredictable and, if you are lucky, your program will crash.
    Here is an Example
    typedef unsigned short USHORT;
    #include <iostream>
    int main() {
       USHORT * pNumber = new USHORT;
       *pNumber = 10;
       std::cout << "*pNumber : " << *pNumber << std::endl;
       delete pNumber;
       long * pLNumber = new long;
       *pLNumber = 90000;
       std::cout << "*pLNumber: " << *pLNumber << std::endl;
       *pNumber = 20;      // BAD statement!, this was deleted!
       std::cout << "*pNumber : " << *pNumber  << std::endl;
       std::cout << "*pLNumber: " << *pLNumber  << std::endl;
       return 0;
    }
    When we run this application the result could be:
    *pNumber : 10
    *pLNumber: 90000
    *pNumber : 20
    *pLNumber: 90000

    You can download this example here (needed tools can be found in the right menu on this page).

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.