您的位置:首页 > 编程语言 > C语言/C++

C/C++内存管理解决方法

2007-05-22 08:30 495 查看
工作两年来发现公司所有的C/C++项目在进行系统设计的时候,仍然将内存管理的设计放到很低的一个层次上:那个模块分配内存、那个模块释放内存、什么时候释放……。但是这样做效果并不好,最终仍然是深深的陷入到内存维护的泥潭之中。

从网上查了一下有关C/C++内存管理方面的知识,总结得到解决方案,但是还没有实践,不知是否可行。

C++的内存管理方法:我的解决方法是,设计统一的Allocator接口,每个模块设计之初就应该选择正确的Allocator。这个Allocator关注的是选择什么分配策略的内存池。接下来一步,是要使用boost库中的shared_ptr。应该将所有的指针都转为使用shared_ptr,这样就可以防止使用无效内存,免去内存管理的烦恼。需要注意的是,shared_ptr不能删除它所维护的指针,但是我认为应该添加这一功能。

C的内存管理方法:设计一个内存分配和释放的通用接口,每个模块的内存分配和释放都使用这个接口,在模块初始化时实例化这个接口。C中没有构造函数、析构函数的概念,使得让人发挥的地方很少。

我设计的C内存管理接口:

typedef struct IMemTool
{
/*******************************************************************************
Function: allocate a memory.
* Param: @pTool: the IMemTool, cannot be 0
* @uiSize: the allocated size in bytes. cannot be 0.
* @destruct: the callback function. it is called when the allocated
* memory is to be freed.
* @pcFile: enabled when _MTDEBUG is defined. save the file name when
* the function is called
* @uiLineNo: enabled when _MTDEBUG is defined. save the line number
* when the function is called.
* Return: the allocated memory if succeed, otherwise return NULL.
* Author: manan
* Date: 2007.5.21
* History:
* [cgc, 2007.5.21] Add function
*******************************************************************************/
#ifdef _MTDEBUG
void* (*Malloc)(struct IMemTool *pTool,
unsigned int uiSize,
void (*destruct)(void*),
const char* pcFile,
unsigned int uiLineNo);
#else
void* (*Malloc)(struct IMemTool *pTool,
unsigned int uiSize,
void (*pfnDestructValue)(void*));
#endif

/*******************************************************************************
* Function: free a memory.
*******************************************************************************/
void (*Free)(struct IMemTool *pTool, void* pValue);

/*******************************************************************************
* Function: Clear the memory tool. if defined _MTDEBUG, the function will print
* the memory that user didnot freed to the standard output.
* After call this function, the user can continue to use the IMemTool
*******************************************************************************/
void (*Clear)(struct IMemTool* pTool);

/*******************************************************************************
* Name: Destruct
* Function: Destruct the memory tool. if defined _MTDEBUG, the function will
* print the memory that user didnot freed to the standard output.
* After call this function, the user cannot continue to use the
* IMemTool
*******************************************************************************/
void (*Destruct)(struct IMemTool* pTool);
} IMemTool;

以后只需要实现各种策略的IMemTool接口就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: