关于资源释放的问题

happy2program 2003-01-11 04:56:35
using namespace std;
template<class T>
void getmem(T*& oldmem, int elems) {
typedef int cntr; // Type of element counter
const int csz = sizeof(cntr); // And size
const int tsz = sizeof(T);
if(elems == 0) {
free(&(((cntr*)oldmem)[-1]));
return;
}
T* p = oldmem;
cntr oldcount = 0;
if(p) { // Previously allocated memory
// Old style:
// ((cntr*)p)--; // Back up by one cntr
// New style:
cntr* tmp = reinterpret_cast<cntr*>(p);
p = reinterpret_cast<T*>(--tmp);
oldcount = *(cntr*)p; // Previous # elems
}
T* m = (T*)realloc(p, elems * tsz + csz);
//require(m != 0);
*((cntr*)m) = elems; // Keep track of count
const cntr increment = elems - oldcount;
if(increment > 0) {
// Starting address of data:
long startadr = (long)&(m[oldcount]);
startadr += csz;
// Zero the additional new memory:
memset((void*)startadr, 0, increment * tsz);
}
// Return the address beyond the count:
oldmem = (T*)&(((cntr*)m)[1]);
}
template<class T>
inline void freemem(T * m) { getmem(m, 0); }

请问free(&(((cntr*)oldmem)[-1]))这一句如何解释,特别是[-1]是什么意思呀!

...全文
46 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧