题目:监控应用程序的内存申请和释放
描述:
不考虑多线程,使用动态单链表的方式进行操作,在应用程序申请内存时,需要把该内存节点信息插入链表进行记录,
应用程序释放内存,把相应内存节点的信息从链表中删除,在应用程序退出时,如果链表仍然存在节点,说明存在
内存泄露,应用程序不存在内存泄露,则链表为空。
请大侠们用C语言编写出内存的申请和释放的封装函数。
MLCmalloc() 封装了malloc ,同时将信息插入链表操作
MLCfree() 封装了free ,同时将信息从链表中删除
- //by CSYNYK
- #include <stdio.h>
- #include <string.h>
- #include <windows.h>
- #define _MC 1 // MLCmalloc()的标志
- #define _FE 0 // MLCfree()的标志
- #define _Check -1 //检测内存的标志
- typedef struct _Memory
- {
- unsigned int address;
- struct _Memory *next;
- }Mem, *LinkMem;
- int MemoryContrl(size_t addr,char flag)
- {
- static Mem head;
- LinkMem tmp=head.next, node=&head ;
- if( _MC==flag )
- {
- while(tmp)
- {
- node=tmp;
- tmp=tmp->next;
- }
- node->next=(LinkMem)malloc(sizeof(Mem));
- if(node->next==NULL)
- return 1; //分配失败!
- node=node->next;
- node->address=addr;
- node->next=NULL;
- }
- else if( _FE==flag)
- {
- while(tmp && (tmp->address!=addr))
- {
- node=tmp;
- tmp=tmp->next;
- }
- if(tmp==NULL)
- return -1; //free地址出错!
- else
- {
- node->next=tmp->next;
- free(tmp);
- }
- }
- else
- return (int)( head.next? head.next->address :0 ); //带头结点的链表
- return 0;
- }
- void *MLCmalloc(size_t size)
- {
- void *pMalc=malloc(size);
- if(pMalc==NULL)
- return NULL;
- else if(MemoryContrl((size_t)pMalc, _MC)==1)
- {
- free(pMalc); //动态链建立失败时释放此次分配的空间
- return NULL;
- }
- else
- return pMalc;
- }
- void MLCfree(void *ptr)
- {
- if(MemoryContrl((size_t)ptr, _FE)==-1)
- {
- printf("%s/n","被释放的内存地址错误!");
- return ;
- }
- else
- free(ptr);
- }
- size_t CheckLeak() //检查泄漏
- {
- return (size_t)(MemoryContrl((size_t)0, _Check));
- }
- int main()
- {
- char **p=NULL;
- char *str="1234567890098765432";
- char *tmp,i;
- p=(char **)MLCmalloc(10*sizeof(char**));
- printf("分配p=%#x/n",p);
- for( i=0;i<10; i++)
- {
- p[i]=(char *)MLCmalloc(20*sizeof(char *));
- sscanf_s(str,"%s",p[i]);
- }
- for( i=0; i<10; i++)
- printf("&p[%d]=%#x *p[%d]=%s/n",i,p[i],i,p[i]);
- printf("释放p=%#x/n",p[2]); //不安正常顺序释放,让下面的代码来检测泄漏。
- MLCfree(p[2]);
- while((tmp=(char*)CheckLeak())!=0) //检测是否有泄漏空间
- {
- MLCfree(tmp); //释放检测到的泄漏空间
- printf("tmp=%#x/n",tmp);
- }
- return 0;
- }