returns the number of bytes in a memory page, where "page" is a fixed-length block, the unit for memory allocation and file mapping performed by mmap(2).
sbrk() #include <unistd.h> void *sbrk(intptr_t increment); //intptr_t 是int的别名, _t都可以认为是int的别名,偶尔是short 或long etc调整动态内存/虚拟内存的大小, increments the program's data space by increment bytes. Calling sbrk() with an increment of 0 can be used to find the current location of the program break.(当前动态分配内存的末尾位置)(程序断点,program break,可以理解为offset的位置),成功返回the previous program break,失败返回(void*)-1
increment>0表示申请动态内存, 就是内存空间变大
increment=0表示获取当前动态内存的末尾地址, 就是内存空间不变
increment<0表示释放动态内存, 就是内存空间变小
#include<stdlib.h> #include<unistd.h> //使用sbrk()获取一个有效地址 void* pv=sbrk(0); if((void*)-1==pv) perror("sbrk"),exit(-1); //使用sbrk()在当前位置基础上申请一个int长度的内存 void* p2=sbrk(sizeof(int)); if((void*)-1==p2) perror("sbrk"),exit(-1);Note:虽然sbrk()既能申请动态内存, 也能释放动态内存, 但是使用sbrk函数申请动态内存时更加方便,��般来说, 使用sbrk函数申请比较小块的动态内存时, 操作系统会映射1个内存页大小的内存空间, 当申请的动态内存超过1个内存也时, 系统会再次映射1个内存页的大小, 当所有动态内存释放完毕时, 系统不会保留任何的动态内存映射, 与malloc()相比, 比较节省内存空间, 也不会申请额外的存储空间, 但是频繁分配时效率没有malloc()高
brk() #include <unistd.h> int brk(void *addr);调整动态内存/虚拟内存的大小, sets the end of the data segment to the value specified by addr,成功返回0,失败返回-1, 设errno为ENOMEM
如果addr>原来的末尾地址,申请动态内存, 内存空间变大
如果addr=原来的末尾地址,内存空间不变
如果addr<原来的末尾地址,释放动态内存, 内存空间变小
//使用brk()释放动态内存 #include<stdlib.h> #include<unistd.h> int res=brk(pv); if(-1==res) perror("brk"),exit(-1);Note:虽然brk()既能申请动态内存, 又能释放动态内存, 但是释放动态内存更加方便, 而sbrk()申请动态内存更加方便, 因此一般情况下两个函数搭配使用, sbrk()专门用于申请, brk()专门用于释放
Memory LeakA memory leak occurs when allocated memory is never used again but is not freed !!!A problem with memory leaks is that the memory cannot be reclaimed and used later. The amount of memory available to the heap manager is decreased. If memory is repeatedly allocated and then lost, then the program may terminate when more memory is needed but malloc() cannot allocate it because it ran out of memory. In extreme cases, the operationg system may crash
losing the address:
int *pi=(int*)malloc(sizeof(int)); *pi=5; //之前申请的内存已经无法释放了,因为address已经丢了 … pi=(int*)malloc(sizeof(int);Hidden memory leaks,Memory leaks can also occur when the program should release memory but does not. A hidden memory leak occurs when an object is kept in the heap even thouth the object is no longrer needed. This is frequently the result of programmer oversight. The primary problem with this type of leak is that the obkect is using memory that is no longer nedded and should be returned to the heap. In the worst case, the heap manager may not be able to allocate memory when requested, possibly forcing the program to terminate. At best, we are holding unneeded memory.