![](https://csdnimg.cn/release/download_crawler_static/86330903/bg3.jpg)
動態分配與靜態分配,二者最大的區別在於:1.直到RunTime的時候,執行動態分配,而在
compiletime的時候,就已經決定好了分配多少Text+Data+BSS+Stack。2.通過malloc()動態分
配的內存,需要程序員手工調用free()釋放內存,否則容易導致內存洩露,而靜態分配的內存則
在進程執行結束後系統釋放(Text,Data),但Stack段中的數據很短暫,函數退出立即被銷毀。
我們使用幾個示例小程序,加深理解
/*@filename:example2.c*/
#include<stdio.h>
intmain(intargc,char*argv[])
{
chararr[]="helloworld";/*Stack段,rw*/
char*p="helloworld"; /*Text段,字符串直接量,rx*/
arr[1]='l';
*(++p)='l'; /*出錯了,Text段不能write*/
return0;
}
PS:變量p,它在Stack段,但它所指的”helloworld”是一個字符串直接量,放在Text段。
/*@filename:example_2_2.c*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char*get_str_1()
{
charstr[]="helloworld";
returnstr;
}