background image

 if(!allocList) 
 return; 
 for(i = allocList->begin(); i != allocList->end(); i++) 
 { 
 if((*i)->address == addr) 
 { 
 allocList->remove((*i)); 
 break; 
 } 
 } 
 }; 
 现在,在我们的程序退出之前,allocList 存储了没有被释放的内存分配。为了看到它们是
什么和在哪里被分配的,我们需要打印出 allocList 中的数据。我使用了 Visual C++中的
Output

 

窗口来做这件事情。

 void DumpUnfreed() 
 { 
 AllocList::iterator i; 
 DWORD totalSize = 0; 
 char buf[1024]; 

 if(!allocList) 
 return; 

 for(i = allocList->begin(); i != allocList->end(); i++) { 
 sprintf(buf, "%-50s: LINE %d, ADDRESS %d %d unfreed ", 
 (*i)->file, (*i)->line, (*i)->address, (*i)->size); 
 OutputDebugString(buf); 
 totalSize += (*i)->size; 
 } 
 sprintf(buf, "----------------------------------------------------------- "); 
 OutputDebugString(buf); 
 sprintf(buf, "Total Unfreed: %d bytes ", totalSize); 
 OutputDebugString(buf); 
 }; 
 现在我们就有了一个可以重用的代码,用来监测跟踪所有的内存泄漏了。这段代码可以
用来加入到所有的项目中去。虽然它不会让你的程序看起来更好,但是起码它能够帮助你
检查错误,让程序更加的稳定。