【c语言】分配内存与释放内存

时间:2023-03-09 06:00:04
【c语言】分配内存与释放内存

提示:现在内存区定出一片相当大的连续空间(如1000字节)。然后开辟与释放都在此空间进行。假设指针变量p原已指向未用空间的开头,调用alloc(n)后,开辟了n个字节可供程序适使用。现在需要使 p的值变为p+n,表示空白未用区从p+n地址开始,同时要将开辟区的起始地址(p)作为函数值返回,以表示可以利用从此点开始的单元。如果要开辟的区太大(n大),超过了预想的(1000)字符,则alloc(n)函数返回指针NULL,表示开辟失败。

#include <stdio.h>

#define LEN (1000)

unsigned char base[LEN];
unsigned char *p=(unsigned char *)base; void *Alloc(unsigned int n)
{
unsigned char *pp=p;
if(p+sizeof(unsigned int)+n<base+LEN&&n>)
{
*(unsigned int*)p=n;
p+=sizeof(unsigned int)+n;
pp+=sizeof(unsigned int);
}
else
{
pp=NULL;
}
return pp;
} void Free(unsigned char *ptr)
{
if(!ptr)
return;
p-=sizeof(unsigned int)+*(unsigned int *)(ptr-sizeof(unsigned int));
} int main()
{
unsigned char *a=NULL;
printf("base=%p,p=%p,a=%p\n",base,p,a);
a=Alloc();
printf("base=%p,p=%p,a=%p\n",base,p,a);
Free(a);
printf("base=%p,p=%p,a=%p\n",base,p,a);
return ;
}

相关文章