写在前面:小生纯业余选手,开此博仅仅是为了积累,纯当笔记来用。如有看官光临小生博客,请不要相信我的代码就是正确的。如果您发现了错误也恳请耽误您一点时间,请您在下面指出来,不胜感激!
如果发现一些笔记的说法完全是错误的请建议我删除!
在malloc的底层有sbrk,brk两个函数
sbrk,brk用来分配和释放内存
sbrk返回没有被映射的虚拟地址的首地址,通常sbrk与brk配合使用,用sbrk(0)获取未被映射的首地址,用brk分配所需要的内存的大小!(以后补图)
示例代码,每一段注释代码说明一点问题
#include<iostream>
#include<unistd.h>
#include<stdio.h>
using namespace std;
int main()
{
/*
cout << "pid = "<< getpid()<<endl;
int *p = static_cast<int*>(sbrk(0));
*p = 4;
*/
/*
int *p = static_cast<int*>(sbrk(sizeof(int)));
*p = 4;
printf("%d\n",*p);
printf("%p\n",p);
*/
/*
int *pp = static_cast<int*>(sbrk(0));
brk(pp+4000);
*(pp+4) = 4;
printf("%d\n",*pp);
printf("%d\n",*(pp+4));
printf("%d\n",*(pp+5));
printf("%d\n",*(pp+4000));
printf("%d\n",*(pp+8001));
*/
/*
int *p = static_cast<int*>(sbrk(0));
int *p1 = static_cast<int*>(sbrk(4));
int *p2 = static_cast<int*>(sbrk(4));
int *p3 = static_cast<int*>(sbrk(4));
int *p4 = static_cast<int*>(sbrk(4));
int *p5 = static_cast<int*>(sbrk(4));
int *p200 = static_cast<int*>(sbrk(200));
int *p201 = static_cast<int*>(sbrk(4));
int *t = static_cast<int*>(sbrk(0));
cout << "p1 = "<<p1<<endl;
cout << "p2 = "<<p2<<endl;
cout << "p3 = "<<p3<<endl;
cout << "p4 = "<<p4<<endl;
cout << "p5 = "<<p5<<endl;
cout << "p200 = "<<p200<<endl;
cout << "p201 = "<<p201<<endl;
cout << "t = "<< t <<endl;
cout << "pid = "<< getpid()<<endl;
int *tt = t;
*tt = 88;
brk(tt+4000);
*(tt+4000) = 99;
cout << "*tt = "<<*tt<<",*(tt+1) = "<<*(tt+4000)<<endl;
*/
/*
int *p = static_cast<int*>(sbrk(0));
int *q = p;
for(int i = 1;i < 10;i++)
{
brk(q+1);
*q = i;
q = static_cast<int*>(sbrk(0));
}
q = p;
int *r = static_cast<int*>(sbrk(0));
while(q != r)
{
printf("%d\n",*q);
q++;
}
for(int i = 0;i<10;i++)
{
brk(r-1);
}
*/
/*
int *p = static_cast<int*>(sbrk(0));
brk(p+1);
*p = 4;
printf("*p=%d\n",*p);
brk(p);
*p = 0;
printf("*P=%d\n",*p);
*/
while(1);
return 0;
}