新聞中心
本章將講解 C 中的動態(tài)內(nèi)存管理。C 語言為內(nèi)存的分配和管理提供了幾個函數(shù)。這些函數(shù)可以在

創(chuàng)新互聯(lián)專注于岢嵐網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠為您提供岢嵐?fàn)I銷型網(wǎng)站建設(shè),岢嵐網(wǎng)站制作、岢嵐網(wǎng)頁設(shè)計、岢嵐網(wǎng)站官網(wǎng)定制、微信小程序定制開發(fā)服務(wù),打造岢嵐網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供岢嵐網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。
| 序號 | 函數(shù)和描述 |
|---|---|
| 1 | void *calloc(int num, int size); 該函數(shù)分配一個帶有 function allocates an array of num 個元素的數(shù)組,每個元素的大小為 size 字節(jié)。 |
| 2 | void free(void *address); 該函數(shù)釋放 address 所指向的h內(nèi)存塊。 |
| 3 | void *malloc(int num); 該函數(shù)分配一個 num 字節(jié)的數(shù)組,并把它們進(jìn)行初始化。 |
| 4 | void *realloc(void *address, int newsize); 該函數(shù)重新分配內(nèi)存,把內(nèi)存擴(kuò)展到 newsize。 |
動態(tài)分配內(nèi)存
編程時,如果您預(yù)先知道數(shù)組的大小,那么定義數(shù)組時就比較容易。例如,一個存儲人名的數(shù)組,它最多容納 100 個字符,所以您可以定義數(shù)組,如下所示:
char name[100];
但是,如果您預(yù)先不知道需要存儲的文本長度,例如您想存儲有關(guān)一個主題的詳細(xì)描述。在這里,我們需要定義一個指針,該指針指向未定義所需內(nèi)存大小的字符,后續(xù)再根據(jù)需求來分配內(nèi)存,如下所示:
#include
#include
#include
int main(){
char name[100];
char *description;
strcpy(name, "Zara Ali");
/* 動態(tài)分配內(nèi)存 */
description = malloc( 200 * sizeof(char) );
if( description == NULL ){
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else{
strcpy( description, "Zara ali a DPS student in class 10th");
}
printf("Name = %s\n", name );
printf("Description: %s\n", description );
}
嘗試一下
當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
Name = Zara Ali Description: Zara ali a DPS student in class 10th
上面的程序也可以使用 calloc() 來編寫,只需要把 malloc 替換為 calloc 即可,如下所示:
calloc(200, sizeof(char));
當(dāng)動態(tài)分配內(nèi)存時,您有完全控制權(quán),可以傳遞任何大小的值。而那些預(yù)先定義了大小的數(shù)組,一旦定義則無法改變大小。
重新調(diào)整內(nèi)存的大小和釋放內(nèi)存
當(dāng)程序退出時,操作系統(tǒng)會自動釋放所有分配給程序的內(nèi)存,但是,建議您在不需要內(nèi)存時,都應(yīng)該調(diào)用函數(shù) free() 來釋放內(nèi)存。
或者,您可以通過調(diào)用函數(shù) realloc() 來增加或減少已分配的內(nèi)存塊的大小。讓我們使用 realloc() 和 free() 函數(shù),再次查看上面的實(shí)例:
#include
#include
#include
int main(){
char name[100];
char *description;
strcpy(name, "Zara Ali");
/* 動態(tài)分配內(nèi)存 */
description = malloc( 30 * sizeof(char) );
if( description == NULL ){
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else{
strcpy( description, "Zara ali a DPS student.");
}
/* 假設(shè)您想要存儲更大的描述信息 */
description = realloc( description, 100 * sizeof(char) );
if( description == NULL ){
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else{
strcat( description, "She is in class 10th");
}
printf("Name = %s\n", name );
printf("Description: %s\n", description );
/* 使用 free() 函數(shù)釋放內(nèi)存 */
free(description);
}
嘗試一下
當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
Name = Zara Ali Description: Zara ali a DPS student.She is in class 10th
您可以嘗試一下不重新分配額外的內(nèi)存,strcat() 函數(shù)會生成一個錯誤,因?yàn)榇鎯?description 時可用的內(nèi)存不足。
當(dāng)前標(biāo)題:創(chuàng)新互聯(lián)C語言教程:C語言內(nèi)存管理
轉(zhuǎn)載來源:http://fisionsoft.com.cn/article/djepsjs.html


咨詢
建站咨詢
