Next
Previous
8. Stack techniquesIf 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 |