郑州网站建设维护,网站建站代理,网站怎么做话术,群晖套件wordpress内存申请与释放 前面的内存为实际内存#xff0c;后面的交换空间为虚拟内存
当申请空间小于等于内存时#xff0c;先使用内存。
当申请空间d大于内存时#xff0c;使用内存虚拟内存
1、判断依据
申请1个G的空间
#includestdio.h
#includestdlib.h
#inc…内存申请与释放 前面的内存为实际内存后面的交换空间为虚拟内存
当申请空间小于等于内存时先使用内存。
当申请空间d大于内存时使用内存虚拟内存
1、判断依据
申请1个G的空间
#includestdio.h
#includestdlib.h
#includeunistd.h
#includeassert.h
#includestring.h
int main()
{char*s(char*)malloc(1024*1024*1024);assert(s!NULL);memset(s,0,1024*1024*1024);printf(main over!\n);sleep(3);exit(0);
}使用前 使用后 进程结束 没有free进程结束后所有分配给该进程的资源都被回收。
申请2个G的空间
#includestdio.h
#includestdlib.h
#includeunistd.h
#includeassert.h
#includestring.h
int main()
{char*s(char*)malloc(1024*1024*1024*2);assert(s!NULL);memset(s,0,1024*1024*1024*2);printf(main over!\n);sleep(3);exit(0);
} 使用前 进程结束 判断依据
① 申请的空间 物理内存空间 ② 申请的空间 物理内存空间 虚拟内存空间 上述两种情况是可以成功的。
如果申请空间大于物理内存空间虚拟内存空间那么申请空间将失败 2、申请了一个空间没有free进程结束空间是否被回收
有第一个可知没有free进程结束后所有分配给该进程的资源都被回收。
3、malloc 与 fork
父进程堆区申请的空间复制后子进程也会有一份也需要释放
#includestdio.h
#includestdlib.h
#includeunistd.h
#includeassert.h
#includestring.hint main(){char * s (char*)malloc(128);assert( s ! NULL );pid_t pid fork();assert( pid ! -1 );if ( pid 0 ){strcpy(s,child);}else{strcpy(s,parent);}printf(s%s\n,s);sleep(1);printf(s%s\n,s);free(s);exit(0);}思考如果两次结果打印相同代表使用同一块空间如果不同代表使用不同空间
结果 子进程是子进程的空间父进程是父进程的空间
父进程在堆区申请的空间也会被复制到子进程中
注意free只能写一次但是父子进程都free了相当于free了两次