C++的一个内存分配问题(有关指针的操作)
以下是C++STL程序员开发指南的一段程序(p114页),调试出现问题,请大家帮忙看看,代码如下:
#ifndef EX05H
#define EX05H
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;
template <class T>
void getmem(T*& oldMem,int elems)
{
typedef int cntr;
const int csz = sizeof(cntr);
const int tsz = sizeof(T);
if (elems==0)
{
free((&(((cntr*)oldMem))[-1]));
return;
}
T * p = oldMem;
cntr oldCount = 0;
if(p)
{
int * tmp = reinterpret_cast<cntr*>(p);
reinterpret_cast<T*>(--tmp);
oldCount=*(cntr*)p;
}
T* m=(T*)realloc(p, (elems*tsz) + csz);
if(m==NULL)
{
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);}
#endif
#include "ex05.h"
#include <iostream>
using namespace std;
int main()
{
int *p = NULL;
getmem(p,10);
for (int i =0;i<10;i++)
{
cout<<p[i]<<' ';
p[i]=i;
}
cout<<endl;
getmem(p,20);
for (int j=0;j<20;j++)
{
cout<<p[j]<<' ';
p[j]=j;
cout<<endl;
}
getmem(p,25);
for (int k=0;k<25;k++)
{
cout<<p[k]<<' ';
}
freemem(p);
cout<<endl;
float * f =0;
getmem(f,3);
for(int u=0;u<3;u++)
{
cout<<f[u]<<' ';
f[u]=u+3.14159;
}
cout<<endl;
getmem(f,6);
for (int v=0;v<6;v++)
{
cout<<f[v]<<' ';
freemem(f);
}
int cc;
cin>>cc;
return 0;
}
主要意思是oldmem并没有指向内存的开始空间把内存的起始空间给计数器(cntr)使用,调试的时候总是指针出现问题。
望各位大侠,帮忙找找问题。