HeapCheck:
1. Disclaimer/Authors
2. Features
3. Introduction
4. Usage
5. Configuration
6. Debugging tools
7. UNIX gurus
8. Stack techniques
9. Known bugs
10. Contact me
11. Get 1.34
12. Get 1.2 (stable)
13. PDF manual
14. WinCE patch for 1.2
 
Back to HomePage
  Next Previous

8. Stack techniques

If you are like me, you probably use code like this sometimes:

void f()
{
    // you should have used std::string 
    // or std::vector!
    char a[100];
    ...		  
}

Unfortunately, you don't have the automatic HeapCheck's checks for buffers allocated this way. There is a way around this, if you code in C++. Place this template/macro in a commonly accessed header file:

template <class T>
class Array {
public:
    Array(T *p):_p(p) 
    ~Array() { delete [] _p; }

    operator T*() { return _p; }
    T& operator [](int offset) {
         return _p[offset];
    }
    T *GetPtr() { return _p; }

private:
    T *_p;
};

#define ARRAY(x,y,z) Array<x> y(new x[z])

and then, when you need a temporary array, use it like this:

void f()
{
    ARRAY(char,a,100);

or, directly:

void f()
{
    Array<char> a(new char[100]);

As you see, this way heap space is used for your arrays, and it is automatically freed when the variable goes out of scope, just like a stack-based array. So, you get the best of both worlds: automatic freeing (through the template) and bounds checking (through HeapCheck). This technique also lowers your stack usage, which could mean something if you use recursive algorithms.


Next Previous