C language tutorial
/ C 內存管理
C 內存管理
本章將講解 C 中的動態(tài)內存管理。C 語言為內存的分配和管理提供了幾個函數(shù)。這些函數(shù)可以在 <stdlib.h> 頭文件中找到。
序號 | 函數(shù)和描述 |
---|---|
1 | void *calloc(int num, int size); 該函數(shù)分配一個帶有 num 個元素的數(shù)組,每個元素的大小為 size 字節(jié)。 |
2 | void free(void *address); 該函數(shù)釋放 address 所指向的h內存塊。 |
3 | void *malloc(int num); 該函數(shù)分配一個 num 字節(jié)的數(shù)組,并把它們進行初始化。 |
4 | void *realloc(void *address, int newsize); 該函數(shù)重新分配內存,把內存擴展到 newsize。 |
動態(tài)分配內存
編程時,如果您預先知道數(shù)組的大小,那么定義數(shù)組時就比較容易。例如,一個存儲人名的數(shù)組,它最多容納 100 個字符,所以您可以定義數(shù)組,如下所示:
char name[100];
但是,如果您預先不知道需要存儲的文本長度,例如您向存儲有關一個主題的詳細描述。在這里,我們需要定義一個指針,該指針指向未定義所學內存大小的字符,后續(xù)再根據(jù)需求來分配內存,如下所示:
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(){ char name[100]; char *description; strcpy(name, "Zara Ali"); /* 動態(tà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 );}
當上面的代碼被編譯和執(zhí)行時,它會產生下列結果:
Name = Zara AliDescription: Zara ali a DPS student in class 10th
上面的程序也可以使用 calloc() 來編寫,只需要把 malloc 替換為 calloc 即可,如下所示:
calloc(200, sizeof(char));
當動態(tài)分配內存時,您有完全控制權,可以傳遞任何大小的值。而那些預先定義了大小的數(shù)組,一旦定義則無法改變大小。
重新調整內存的大小和釋放內存
當程序退出時,操作系統(tǒng)會自動釋放所有分配給程序的內存,但是,建議您在不需要內存時,都應該調用函數(shù) free() 來釋放內存。
或者,您可以通過調用函數(shù) realloc() 來增加或減少已分配的內存塊的大小。讓我們使用 realloc() 和 free() 函數(shù),再次查看上面的實例:
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(){ char name[100]; char *description; strcpy(name, "Zara Ali"); /* 動態(tà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."); } /* 假設您想要存儲更大的描述信息 */ 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ù)釋放內存 */ free(description);}
當上面的代碼被編譯和執(zhí)行時,它會產生下列結果:
Name = Zara AliDescription: Zara ali a DPS student.She is in class 10th
您可以嘗試一下不重新分配額外的內存,strcat() 函數(shù)會生成一個錯誤,因為存儲 description 時可用的內存不足。