检测内存泄露的方法:

C++内存泄漏:原因、预防、定位 通过编写自定义的内存分析工具,可以在应用程序中插入代码来跟踪内存分配和释放的情况,从而帮助定位内存泄漏。 阅读详情
http://blog.csdn.net/wei801004/archive/2006/08/11/1050394.aspx
 检测内存泄露的方法:

C++中检测内存泄漏可以引入系统定义的宏来查看,内存在哪个位置泄漏

文件开始处加入下列定义
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

程序退出时加入以下函数:

_CrtDumpMemoryLeaks();

使用环境:VS2003

如果在系统中出现了内存泄露,在输出窗口会出现这样的信息:

Detected memory leaks!
Dumping objects ->
d:/program files/microsoft visual studio .net 2003/vc7/include/crtdbg.h(692) : {47} normal block at 0x003F2C88, 1024 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.



检测内存泄露的常用手段:debugnew收藏

新一篇: 安装 PrintManager 和 SQL Server 所遇到的问题 | 

检测内存泄露的工具:debugnew

网上有一个流传甚广的检测内存泄露的工具:debugnew(debugnew.h/debugnew.cpp)
用法很简单,把debugnew.cpp放在项目里一起编译,需要检测的文件把debugnew.h嵌在文件的最前面。

为方便使用,对源代码做了一些小的改动。

下面是一些简单的说明:

1、new 的重载
void* operator new (size_t size, const char* file, int line);        ⑴
void* operator new [] (size_t size, const char*  file, int line);      ⑵

在需要检测的文件里,重定义new
#define new new(__FILE__, __LINE__)

造成的结果:
ClassName *p = new ClassName; => ClassName *p = new(__FILE__, __LINE__) ClassName;
// 实际会调用void* operator new (size_t size, const char* file, int line);

ClassName **pp = new classname[count]; => ClassName **pp = new(__FILE__, __LINE__) ClassName[count];
// 实际会调用void* operator new [] (size_t size, const char*  file, int line);

这其实是利用了placement new的语法,通过一个简单的宏,就可以把普通的new操作对应到相应的重载( ⑴,⑵ )上去。

2、delete 的重载
void operator delete (void* p, const char* file, int line);                   ⑶
void operator delete [] (void* p, const char* file, int line);                ⑷
void operator delete (void* p);                                               ⑸
void operator delete [] (void* p);                                            ⑹

因为没有类似于placement new的语法,所以就不能用一个宏来替换替换delete了。要调用带有更多信息的delete操作符,只能修改源代码了。
delete p; => delete ( p, __FILE__, __LINE__ );
delete []pp; => delete [] ( pp, __FILE__, __LINE__ );
但这个工作很烦琐,如果并不需要多余的信息的话,简单地重载delete( ⑸,⑹ )就可以了。

3、检测和统计
程序开始时,在debugnew.cpp中会创建一个DebugNewTracer对象
在重载的new操作符( ⑴,⑵ )中,每一次内存分配都会被记录,而在delete( ⑶,⑷,⑸,⑹ )中则会删除相应的记录。
当程序结束,DebugNewTracer对象被销毁,它的析构函数会dump剩余的记录,这就是泄露的内存了。

在原有代码的基础上,增加了记录size的功能,这样可以在每次new和delete时,看到实际占用的内存。所有信息可以dump出来,也可以写入log。

4、在MFC项目里使用debugnew

MFC对检查内存泄露提供了很好的支持,一般情况下,在MFC项目中加入cpp文件时,MFC会自动在文件头加入如下的代码:

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

这时候,就用不上我们自己的debugnew了。

现在,你有一个MFC项目,另外有非MFC的C++项目,MFC项目要引用 C++项目提供的算法。

现在,你有一个MFC项目,另外有非MFC的C++项目,MFC项目要引用 C++项目提供的算法。

通常的做法是:将C++项目编译成一个*,lib,然后和MFC项目一起链接。

那么问题出现了:

MFC能检测到MFC项目中的内存泄露并给出具体的文件名及行号,对于C++项目,尽管可以检测到泄露,但不能给更多的信息;如果在C++项目中加入debugnew,链接时则会出现错误。

解决办法:

在C++项目中,不要加入debugnew,只在要检测泄露的cpp文件中引用debugnew.h就可以了。


5、源代码

********************************************************
debugnew.h:

/*
 filename: debugnew.h
 
 This code is based on code retrieved from a web site. The
 author was not identified, so thanks go to anonymous.

 This is used to substitute a version of the new operator that
 can be used for debugging memory leaks. To use it:
 
 - In any (all?) code files #include debugnew.h. Make sure all
  system files (i.e. those in <>'s) are #included before
  debugnew.h, and that any header files for your own code
  are #included after debugnew.h. The reason is that some
  system files refer to ::new, and this will not compile
  if debugnew is in effect. You may still have problems
  if any of your own code refers to ::new, or if any
  of your own files #include system files that use ::new
  and which have not already been #included before
  debugnew.h.
 - Add debugnew.cpp to the CodeWarrior project or compile
  it into your Linux executable. If debugnew.cpp is in the
  project, then debugnew.h must be #included in at least
  one source file
*/

#ifndef __DEBUGNEW_H__
#define __DEBUGNEW_H__

#include <map>

#define LOG_FILE

#if defined(LOG_FILE)
#define LOG_FILE_NAME "./debugnew.log"
#endif

void* operator new (std::size_t size, const char* file, int line);
void operator delete (void* p, const char* name, int line);
void* operator new [] (std::size_t size, const char* file, int line);
void operator delete [] (void* p, const char* name, int line);

class DebugNewTracer  {
private:
 
 class Entry  {
 public:
  Entry (char const* file, int line) : _file (file), _line (line) {}
  Entry (char const* file, int line, int size) : _file (file), _line (line), _size (size) {}
  Entry () : _file (0), _line (0), _size (0) {}
  const char* File () const { return _file; }
  int Line () const { return _line; }
  size_t Size () const { return _size; }
 private:
  char const* _file;
  int _line;
  size_t _size;
 };

 class Lock {
 public:
  Lock (DebugNewTracer & DebugNewTracer) : _DebugNewTracer (DebugNewTracer) {
   _DebugNewTracer.lock ();
  }
  ~Lock () {
   _DebugNewTracer.unlock ();
  }
 private:
  DebugNewTracer & _DebugNewTracer;
 };
 typedef std::map<void*, Entry>::iterator iterator;
 friend class Lock;
 public:
 DebugNewTracer ();
 ~DebugNewTracer ();
 void Add (void* p, const char* file, int line);
 void Add (void* p, const char* file, int line, size_t size);
 void Remove (void* p);
 void Dump ();

 static bool Ready;

 private:
 void lock () { _lockCount++; }
 void unlock () { _lockCount--; }

 private:

 std::map<void*, Entry> _map;
 int _lockCount;
 size_t _totalsize;
#if defined(LOG_FILE)
 FILE* _logfp;
#endif
 };

 // The file that implements class DebugNewTracer
 // does NOT want the word "new" expanded.
 // The object DebugNewTrace is defined in that
 // implementation file but only declared in any other file.
#ifdef DEBUGNEW_CPP
DebugNewTracer DebugNewTrace;
#else
#define new new(__FILE__, __LINE__)
extern DebugNewTracer DebugNewTrace;
#endif

#endif//#ifndef __DEBUGNEW_H__


********************************************************
debugnew.cpp:

/*
 filename: debugnew.cpp

 This is used to substitute a version of the new operator that
 can be used for debugging memory leaks. In any (all?) code
 files #include debugnew.h. Add debugnew.cpp to the project.
*/

#include <iostream>
#include <map>

using namespace std;

 // This disables macro expansion of "new".
 // This statement should only appear in this file.
#define DEBUGNEW_CPP

#include "debugnew.h"

DebugNewTracer::DebugNewTracer () : _lockCount (0)
{
  // Once this object is constructed all calls to
  // new should be traced.

 Ready = true;
 _totalsize = 0;
#if defined(LOG_FILE)
 if( (_logfp=fopen(LOG_FILE_NAME,"wt")) == NULL )
 {
  printf(" Error! file: debugnew.log can not open@!/n");
  return;
 } 
 fprintf(_logfp,"new, delete list:/n");
 fflush(_logfp);
#endif
 
}
        
void DebugNewTracer::Add (void* p, const char* file, int line)
{
  // Tracing must not be done a second time
  // while it is already
  // in the middle of executing
 if (_lockCount > 0)
  return;

   // Tracing must be disabled while the map
   // is in use in case it calls new.
 DebugNewTracer::Lock lock (*this);
 _map [p] = Entry (file, line);
}

void DebugNewTracer::Add (void* p, const char* file, int line, size_t size)
{
 // Tracing must not be done a second time
 // while it is already
 // in the middle of executing
 if (_lockCount > 0)
  return;

  // Tracing must be disabled while the map
  // is in use in case it calls new.
 DebugNewTracer::Lock lock (*this);
#if 1
 //´Óȫ·¾¶ÖÐÌáÈ¡ÎļþÃû
 //linuxϵÄgcc,__FILE__½ö½ö°üÀ¨ÎļþÃû£¬windowsϵÄvc,__FILE__°üÀ¨È«Â·¾¶,ËùÒÔÓÐÕâÑùµÄ´¦Àí
 file = strrchr(file,'//')== NULL?file:strrchr(file,'//')+1;
#endif
 _map [p] = Entry (file, line, size);
 _totalsize += size;
#if defined(LOG_FILE)
 fprintf(_logfp,"*N p = 0x%08x, size = %6d,  %-22s, Line: %4d.  totalsize =%8d/n", p, size, file, line, _totalsize);
 fflush(_logfp);
#endif
}


void DebugNewTracer::Remove (void* p)
{
 // Tracing must not be done a second time
 // while it is already
 // in the middle of executing
 if (_lockCount > 0)
  return;

  // Tracing must be disabled while the map
  // is in use in case it calls new.
 DebugNewTracer::Lock lock (*this);

 iterator it = _map.find (p);

 if (it != _map.end ())
 {
  size_t size = (*it).second.Size();
  _totalsize -= size;
#if defined(LOG_FILE)
  fprintf(_logfp,"#D p = 0x%08x, size = %6u.%39stotalsize =%8d/n", p, size, "-----------------------------------  ", _totalsize );
  fflush(_logfp);
#endif
  _map.erase (it);
 }
 else
 {
#if defined(LOG_FILE)
  fprintf(_logfp,"#D p = 0x%08x. error point!!!/n", p );
  fflush(_logfp);
#endif
 }
}

DebugNewTracer::~DebugNewTracer ()
{
 // Trace must not be called if Dump indirectly
 // invokes new, so it must be disabled before
 // Dump is called. After this destructor executes
 // any other global objects that get destructed
 // should not do any tracing.
 Ready = false;
 Dump ();
#if defined(LOG_FILE)
 fclose(_logfp);
#endif
}

// If some global object is destructed after DebugNewTracer
// and if that object calls new, it should not trace that
// call to new.
void DebugNewTracer::Dump ()
{
 if (_map.size () != 0)
 {
  std::cout << _map.size () << " memory leaks detected/n";
#if defined(LOG_FILE)
  fprintf(_logfp, "/n/n***%d memory leaks detected/n", _map.size ());
  fflush(_logfp);
#endif
  for (iterator it = _map.begin (); it != _map.end (); ++it)
  {
   char const * file = it->second.File ();
   int line = it->second.Line ();
   int size = it->second.Size ();
   std::cout << file << ", "  << line << std::endl;
#if defined(LOG_FILE)
   fprintf(_logfp,"%s, %d, size=%d/n", file, line, size);
   fflush(_logfp);
#endif
  }
 }
 else
 {
  std::cout << "no leaks detected/n";
#if defined(LOG_FILE)
  fprintf(_logfp,"no leaks detected/n");
  fflush(_logfp);
#endif
 }

}

// If some global object is constructed before DebugNewTracer
// and if that object calls new, it should not trace that
// call to new.
bool DebugNewTracer::Ready = false;

void* operator new (size_t size, const char* file, int line)
{
 void * p = malloc (size);
 if (DebugNewTracer::Ready)
  DebugNewTrace.Add (p, file, line, size);
 return p;
}

void operator delete (void* p, const char* file, int line)
{
 file = 0; // avoid a warning about argument not used in function
 line = 0; // avoid a warning about argument not used in function
 
 if (DebugNewTracer::Ready)
  DebugNewTrace.Remove (p);
 free (p);
}
        
void* operator new [] (size_t size, const char*  file, int line)
{
 void * p = malloc (size);
 if (DebugNewTracer::Ready)
  DebugNewTrace.Add (p, file, line, size);
 return p;
}

void operator delete [] (void* p, const char* file, int line)
{
 file = 0; // avoid a warning about argument not used in function
 line = 0; // avoid a warning about argument not used in function
 
 if (DebugNewTracer::Ready)
   DebugNewTrace.Remove (p);
 free (p);
}
        
void* operator new (size_t size)
{
 void * p = malloc (size);
 // When uncommented these lines cause entries in the map for calls to new
 // that were not altered to the debugnew version. These are likely calls
 // in library functions and the presence in the dump of these entries
 // is usually misleading.
 // if (DebugNewTracer::Ready)
 //   DebugNewTrace.Add (p, "?", 0);
 return p;
}
 
void operator delete (void* p)
{
 if (DebugNewTracer::Ready)
  DebugNewTrace.Remove (p);
 free (p);
}

//add by yugang
void operator delete [] (void* p)
{
 if (DebugNewTracer::Ready)
  DebugNewTrace.Remove (p);
 free (p);
}

发表于 @ 2004年12月30日 09:54:00|评论(0)|编辑

新一篇: 安装 PrintManager 和 SQL Server 所遇到的问题 | 

C++ vector变量等导致内存泄露问题的解决方法 之前在做一个音频特征提取的批量处理程序,老是出现内存泄露问题,用Visual Leak Detector(VLD)工具做了下检测,检测出了一些问题,解决后还是会有问题。之后继续排查,因为我的代码中,大量的音频相关处理的数据都存成了vector变量,推测是不是vector变量的析构问题,上网查了些资料,现写出解决过程: 1、关于Visual Leak Detector的配置与使用 主要也 阅读详情

相关推荐

debug_new:C / C ++一切内存调试器-开源

警告:较旧的项目可能必须使用-DDEBUG_NEW_CONFIG_HAVE_DEPRECATED进行编译。Debug_New提供了调试内存泄漏的可能性,不仅可以(请注意“ not only”;这只是其功能之一)在一种方式,但是使用内存状态来实现。 -跨平台+跨编译器支持(仅针对c ++使用预处理器和模板-voodoo-magic)-支持C和C ++-支持gcc和g ++-支持pthread和任何posix平台-支持多线程。 -易于使用和安装(只需包含标题并链接源代码)。 -轻松调试内存泄漏。 -轻松调试悬空指针。 -轻松调试解除分配方法的正确性。 -轻松调试数组索引错误(写到末尾时)。 -轻松配置内存使用情况并跟踪内存信息。 -对Visual Studio的点击即转到源支持。 -对new,new [],delete,delete [],malloc,calloc,realloc,free的集成兼容性

DEBUG_NEW

DEBUG_NEW #define new DEBUG_NEW 说明: 帮助查找内存错误。用户在程序中使用DEBUG_NEW,用户通常使用new运算符来从堆上分配。在Debug模式下(但定义了一个DEBUG符号),DEBUG_NEW为它分配的每个对象记录文件名和行号。然后,在用户使用CMemoryState::DumpAllObjectSince成员函数时,每个以DEBUG_NEW分配

Road2010的专栏 1063

耶鲁大学《博弈论》课程——逆向归纳

耶鲁大学《博弈论》课程——逆向归纳

ZYLer_的博客 7887

检测内存泄露的常用手段:debugnew

检测内存泄露的工具:debugnew网上有一个流传甚广的检测内存泄露的工具:debugnew(debugnew.h/debugnew.cpp)用法很简单,把debugnew.cpp放在项目里一起编译,需要检测的文件把debugnew.h嵌在文件的最前面。为方便使用,对源代码做了一些小的改动。下面是一些简单的说明:1、new 的重载void* operator new (size_t size, c

coldcrane的专栏 6337

ensp企业网综合实验(课程设计)

使用MSTP+VRRP技术实现负载均衡以及增加网络的可靠性;出口配置napt;所有用户均为自动获取IP地址;

qq_50829760的博客 1万+

基因的富集分析

通过RNA_seq差异表达分析等获得一组基因,想要进一步了解这些基因可能参与哪些生物学过程,具有哪些功能,一般就会用到基因的富集分析了。现在小麦基因注释信息已经可以获得,目前来看包括两套。一个是TGACv1,另一个就是IWGSC1.0。需要用到一个叫“clusterProfiler”的R包。下面用到的数据集来自TGACv1。1、安装source("https://bioconductor.org/b

xxxxx 1万+

关于 DEBUG_NEW

  #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif (1) 在 MFC 中,可以使用 DEBUG_NEW 宏代替 new 运算符来帮助定位内存泄漏。在程序的“Debug”版本中,DEBUG_NEW将为所分配的每个对象跟踪文件名和

magicsutra的专栏 3889

从零构建MAVLink通信:PX4飞控与QGC的协议握手全解析

本文详细解析了PX4飞控与QGC地面站通过MAVLink协议进行通信的全过程,重点介绍了航点传输协议的状态机设计、INT类型消息的优化优势以及异常处理与调试技巧。通过实战案例和性能优化建议,帮助开发者高效构建无人机通信系统,提升数据传输效率与稳定性。

weixin_29209805的博客 509

[QT编程系列-43]: Windows + QT软件内存泄露的检测方法

在QT程序中,您可以使用一些工具和技术来查找和分析内存泄漏问题。QT提供了内置的内存调试工具,其中包括Qt的调试分析工具(如qdebug、qmlprofiler等)。这些工具可以帮助您检测和分析内存泄漏问题。通过设置适当的宏,在程序运行时会显示内存分配和释放的相关信息。除了QT的内置工具,您还可以使用一些第三方工具来检测内存泄漏,例如Valgrind、AddressSanitizer等。这些工具可以帮助您检测未释放的内存、内存越界访问等问题,并提供详细的报告。

文火冰糖(王文兵)的博客 1万+

Workbench下列车转向架随机振动疲劳分析

结果中添加功率谱响应工具(Response PSD Tool),可以查看几何体以及远程点上的功率谱密度,如下图11所示,这里查看几何体上某一硬点的加速度功率谱密度响应曲线,如下图12所示。结果中添加疲劳工具(Fatigue Tool),查看列车转向架的疲劳寿命情况,这里采用窄带的寿命假设理论,曝光时间为1s指明计算出的疲劳寿命的基本单位是秒,寿命结果如下图14所示,可以看到最大寿命为1e35s,最小寿命为2.3542e18s,注意单位制,可再次基础上将其转换为小时或天。频域上的统计计算,软件很快计算完成。

ansysxuexizhe的博客 2610

【Unity】【Pico】【VR开发】为何PICO打包后真机运行闪退

由于并没有开版权验证,而且闪退后也并没有弹框说版权问题,所以还是怀疑环境有什么地方不对。设置步骤,项目配置都没问题,Build也成功,Unity版本是符合要求的2022LTS版本,但是一在真机上运行就闪退。

每日出拳老爷子的博客 3184

MFC内存泄露检测

这几天一直在检查程序内存泄露的问题,今天终于告一段落。 内存泄露在编制小型应用程序时看不出其危害,但如果是编制24小时运行的大型平台应用程序时,如果有内存泄露,则随着程序的运行,其占用的内存会越来越多,最终导致系统崩溃。因此,内存泄露不容小觑。下面是几天来检查内存泄露的一点经验小结。 1.常规内存泄露的检测 常规内存泄露一般是由于编程者在手动申请内存空间之后没有释放造成的。如用new、malloc()函数或CString的GetBuuffer()函数申请内存空间后没有使用对应的释放语句释放内存空间.

全粘工程师 1752

遗传算法(Genetic Algorithm)详解与实现

遗传算法(Genetic Algorithm, GA)是受自然进化原理启发的一系列搜索算法。通过模仿自然选择和繁殖的过程,遗传算法可以为涉及搜索、优化和学习的各种问题提供高质量的解决方案。同时,它们类似于自然进化,因此遗传算法可以克服传统搜索和优化算法遇到的一些障碍,尤其是对于具有大量参数和复杂数学表示形式的问题。

盼小辉丶的博客 24万+

内存泄露检查的两种方法

内存泄露检查的两种方法——总有一款适合你1.VLD方法1.1使用VLD工具1.2下载与配置1.3测试程序1.4结果分析2._CrtDumpMemoryLeaks方法2.1简单的使用2.2定位内存泄露位置有两种方法分别如下:2.2.1 用VS的监视:2.2.2 加入代码 **_CrtSetBreakAlloc(64);**: 1.VLD方法 1.1使用VLD工具 Visual Leak Dete...

luolei188的博客 3096

【CANoe示例分析】SOMEIPWithvCDL_16

本示例来源于官方提供的示例工程:0004_基于vCDL实现SOMEIP通信_Demo\0004_基于vCDL实现SOMEIP通信_Demo\SOMEIPWithvCDL。

jasonj333 577

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

内存泄露检测

    内存泄露是许多大规模程序中亟待解决的问题,下面是一点资料整理,帮我记忆吧。有VC自带的工具,也有免费的比较成熟的工具。控制台程序编译即可看到效果。// = MemoryLeakDetect.cpp/// 去掉注释观察VS2005自带内存检测工具效果//#define DEFAULT_CRGDBG_MEM_CHECK#ifndef DEFAULT_CRGDBG_MEM_C

dananhai的专栏 2064

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

javascript 内存泄露工具使用

Javascript javascript 内存泄露工具使用 作者:puterjam 日期:2008-12-23 字体大小: 小 中 大 javascript内存泄露的问题一直以来都不受到大家的重视,原因是对用户的影响没有太实际的表现,或许近几年内

Mstr838Wind的专栏 835

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

netty内存检测

 1,内存泄露级别 DISABLED, SIMPLE, ADVANCED, PARANOID; DISABLED(禁用);: 不进行内存泄露的检测; SIMPLE(操作简单): 抽样检测,且只对部分方法调用进行记录,消耗较小,有泄漏时可能会延迟报告,默认级别; ADVANCED(高级): 抽样检测,记录对象最近几次的调用记录,有泄漏时可能会延迟报告; PARANOID(偏执): 每次...

u011820505的博客 1232

如何解决内存泄露:笨方法手动调试

上篇文章介绍了内存泄露以及避免方法,本篇文章介绍当内存泄露发生时,如何解决1. 笨方法手动调试 1 检查代码是否每一个new、malloc 都有对应的 delete、free 2 观察有哪些可能分配内存和释放内存的代码,在其上下添加断点,以debug模式运行 3 打开任务管理器,查看调试程序的内存占用, 4 逐个排除: - 看运行哪些语句时内存占用增加 - 看运行释放内存语句后

quinn的专栏 1010

(转)javascript 内存泄露工具使用

(转)javascript 内存泄露工具使用 javascript内存泄露的问题一直以来都不受到大家的重视,原因是对用户的影响没有太实际的表现,或许近几年内存发展迅速。脚本内存再泄露也不会有太大影响。 当然作为前端开发的同学们,就不能有这样的侥幸心理。出现...

ddl_2014的博客 136

Android监控内存泄露利器-使用Leak Canary

Android监控内存泄露利器---Leak Canary,先看一下,在Android Studio如何集成? 很简单,两步。 1、在build.gradle中添加两行代码。 dependencies { //leakcanay检测内存泄露 start debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3

天外来客1009 1157

检查内存泄露

自己编写的视频处理程序出现了一个问题 每帧的运行时间随着运行时间在不断增长,很大可能是出现了内存泄露,于是学习了一些查看内存泄露的方法。做了两种尝试 一是VS自带的DEBUG下的检测 view pl [html] view plain copy #define CRTDBG_MAP_ALLOC     #include stdlib.h> 

汤圆圆的博客 402

使用xcode4.2检测内存泄露leak的具体位置的两种方法总结 .

原文链接:http://blog.csdn.net/yanxiaoqing/article/details/7174750 转载注明以上文字 第一:出现内存泄露后如图1所示,点击view工具的第三个视图,显示左侧栏,即如图2所示: (图一) 第二:双击泄露的黑色的表示泄露的代码,出现如图三所示 (图二) 第三:红色区域即是表示有泄露的obje

北雪落的专栏 744

IE浏览器内存泄露检测工具

随着Web2.0技术的发展,富客户端的应用可以说是越来越多,给各个浏览器造成很大的压力。以前的测试可能只关注于服务器端,如今却需要研究浏览器端的资源使用情况,如CPU利用率、响应时间和内存占用。根据实际测试中的结果,有相当多的JavaScript代码编写存在缺陷,导致代码在IE浏览器时发生内存泄露,有关泄露的原理,可以参考微软网站上的一篇技术文章,《Understanding and Solv

冷月宫主的专栏 963

c++内存泄露检测,长文慎入!

转自:http://blog.csdn.net/zengraoli/article/details/8905334 关于内存泄露的,今天无意想到,网上找了一下 本篇blog附带的所有工具和代码下载地址如下: http://download.csdn.net/detail/zengraoli/5348827 文中的memcheck晚点的时候在把它打

threadroc的专栏 807

C++经验之检测内存泄露

C++具有动态分配和释放内存的能力,所谓成也萧何败萧何,这种能力如果使用疏忽会造成内存泄露。本文简单介绍2种检测内存泄露的方法。【使用调试器和CRT库】在程序的开头包含如下说明。在VS2010平台上,如果要显示泄露的内存原先分配的地方,需要包括下面第二段(在VS2008上就不用)

lilypp的专栏 951
上一篇: 标准C++类STRING的COPY-ON-WRITE技术(三)
下一篇: Thread Stack Size
skyremember
博客等级 码龄20年 205粉丝 484原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址