在更安全使用malloc()、calloc()、realloc()等內存分配函數的議題中,有許多事可以做,下面的函數模板處理了一函數getmem(),這個函數既可以分配新的內存空間,或者調整已分配內存空間的大小,它把新空間全部置0, 並檢查操作是否成功。這樣,只需要告訴它需要多少空間就行了,這樣做可以減少程序出錯的可能性。函數代碼如下:
- template<class T>
- void getmem(T* &oldmem, int elems)
- {
- typedef int cntr;
- const int csz = sizeof(cntr);
- const int tsz = sizeof(T);
-
- if (0 == elems)
- {
- free(&(((cntr *)oldmem)[-1]));
- return;
- }
-
- T *p = oldmem;
- cntr oldcount = 0;
- if (p)
- {
- cntr *tmp = reinterpret_cast<cntr *>(p);
- p = reinterpret_cast<T *>(--tmp);
- oldcount = *(cntr *)p;
- }
-
- T *m = (T *)realloc(p, elems * tsz + csz);
- if (0 == m)
- {
- cout << "ERROR!" << endl;
- exit(1);
- }
-
- *((cntr *)m) = elems;
- const cntr increment = elems - oldcount;
- if (increment > 0)
- {
- long startadr = (long)&(m[oldcount]);
- startadr += csz;
- memset((void *)startadr, 0, increment * tsz);
- }
-
- oldmem = (T *)&(((cntr *)m)[1]);
- }
-
- template<class T>
- inline void freemem(T *m) { getmem(m, 0); }