对我来说,安全地释放分配的内存始终是一个麻烦。 我的意思是释放所有内存。 因此,我开发了一种简单的方法,可能会对我有所帮助。 我没有在任何项目中使用它,但是无论如何我都会
这是两个文件:
secmem.h
#ifndef secmem_h
#define secmem_h 1
#include<stdlib.h>
void * secureAlloc(size_t size,int Line, char *FileName);
short secureFree(void *ptr);
short freeAll();
#endif
secmem
#include "secmem.h"
#include <stdio.h>
#include <string.h>
struct MemoryList
{
long MemoryAddress;
int line;
char fileName[20];
struct MemoryList *Next;
};
static struct MemoryList *Start,*Last;
void * secureAlloc(size_t size,int Line, char *FileName)
{
long newAddress,newAddress2;
newAddress=(long)malloc(size);
newAddress2=(long)malloc(sizeof(struct MemoryList));
if(Start==NULL)
{
Start=(struct MemoryList *)newAddress2;
Last=Start;
Last->MemoryAddress=newAddress;
Last->line=Line;
strcpy(Last->fileName,FileName);
}
else
{
Last->Next=(struct MemoryList *)newAddress2;
Last=(struct MemoryList *)newAddress2;
Last->MemoryAddress=newAddress;
Last->line=Line;
strcpy(Last->fileName,FileName);
}
return (void *)newAddress;
}
short secureFree(void *ptr)
{
struct MemoryList *Cont,*Prev;
long temp=(long)ptr;
if(ptr!=NULL)
{
free(ptr);
}
else
{
return 1;
}
Cont=Start;
Prev=Cont;
while(Cont)
{
if((long)Cont->MemoryAddress==temp)
{
if(Cont==Start)
{
Start=Cont->Next;
free(Cont);
if(Start==NULL)
{
Last=NULL;
}
return 0;
}
else
{
Prev->Next=Cont->Next;
free(Cont);
if(Prev->Next==NULL)
{
Last=Prev;
}
return 0;
}
}
else
{
Prev=Cont;
Cont=Cont->Next;
}
}
return 1;
}
short freeAll()
{
struct MemoryList *Cont,*Next;
int Count=0;
Cont=Start;
while(Cont)
{
Next=Cont->Next;
printf("File Name: %s, Line Number : %d\n",Cont->fileName,Cont->line);
free(Cont);
Cont=Next;
Count++;
}
printf("Total Freed : %d\n",Count);
}
测试文件: test.c
#include <stdio.h>
#include "secmem.h"
struct test_
{
char *a;
char *b;
char *c;
struct test_ *Next;
}*test;
int main()
{
test=secureAlloc(sizeof(struct test_),__LINE__,__FILE__);
test->a=(char*)secureAlloc(10,__LINE__,__FILE__);
secureFree(test);
freeAll();
return 0;
}
现在如何运作
在test.c中,我调用了secureAlloc,包括行号和文件名。
在程序的最后,我调用了freeAll()函数。
当它运行free all功能时,它还会从请求分配的位置打印所有行号和文件名。
这对于调试很有帮助,并确保所有分配的内存都已释放。
最后一步,只要您确定所有内存都已释放,然后在公共头文件中添加一些宏并删除freeAll()函数
测试
#include <stdio.h>
#include <stdlib.h>
//#include "secmem.h"
#define secureAlloc(a,b,c) malloc(a)
#define secureFree(a) free(a)
struct test_
{
char *a;
char *b;
char *c;
struct test_ *Next;
}*test;
int main()
{
test=secureAlloc(sizeof(struct test_),__LINE__,__FILE__);
test->a=(char*)secureAlloc(10,__LINE__,__FILE__);
secureFree(test);
// freeAll();
return 0;
}
希望这会有所帮助
From: https://bytes.com/topic/c/insights/918837-secure-memory-allocation-free