内存管理:
虚拟内存的分配和释放
sbrk:相对路径,分配方便
brk:绝对路径,整体一次性释放,指针跳转到第一次分配之后的前一个位置
#include<stdio.h>
#include<unistd.h>
//sbrk 和brk 函数的调用
int main()
{
/*printf("%p\n",sbrk(0));
int * int_p = sbrk(4);
*int_p = 32;
printf("%p\n",int_p);
int * dou_p = sbrk(8);
*dou_p = 4.44;
printf("%p\n",dou_p);
sbrk(-14);
printf("%p\n",sbrk(0));
printf("%p\n",sbrk(-16));*/
printf("------------------\n");
printf("%p\n",sbrk(0));
int *p1 = sbrk(0);
printf("%p\n",p1);
brk(p1 +1);
printf("%p\n",p1);
double *p2 = sbrk(0);
brk(p1+1);
printf("%p\n",p2);
brk(p1);
printf("%p\n",sbrk(0));
return 0;
}
0x1f44000
0x1f65000
0x1f65004
0x1f64ffe
0x1f64ffe
---------------------
0x1e3e000
0x1e3e000
0x1e3e000
0x1e3e004
0x1e3e000
内存映射:
//内存的映射
#include<stdio.h>
#include<sys/mman.h>
#include<string.h>
int main(void)
{
//建立映射两页内存(一页4kb)
char *p1 = mmap(NULL,8192,PROT_READ | PROT_WRITE,MAP_ANONYMOUS | MAP_PRIVATE,0,0);
if(p1 == MAP_FAILED )
{
perror("mmap");
return -1;
}
strcpy(p1,"第一页映射内存");
printf("%s\n",p1);
// 解除映射 可以对映社射区部分解除映射,但是必须按页解除
if(munmap(p1,4096) == -1)
{
perror("munmap");
return -1;
}
//printf("%s\n",p1);//断错误,解除映射后,无法找到对应物理内存
char *p2 = p1 + 4096;
strcpy(p2,"第二页映射内存");
printf("%s\n",p2);
if(munmap(p2,1111) == -1)//不管解除多少都会按页(4096)解除对齐
{
perror("munmap");
return -1;
}
return 0;
}
系统调用: