C語言中的動態記憶體分配是什麼?


在這裡,我們將瞭解C語言中的動態記憶體分配。C程式語言提供了多個用於記憶體分配和管理的函式。這些函式可以在<stdlib.h>標頭檔案中找到。以下是用於記憶體分配的函式。

函式描述
void *calloc(int num, int size);此函式分配一個包含**num**個元素的陣列,每個元素的大小(以位元組為單位)為size。
void free(void *address);此函式釋放由address指定的記憶體塊。
void *malloc(int num);此函式分配一個包含**num**個位元組的陣列,並將其保留為未初始化狀態。
void *realloc(void *address, int newsize);此函式重新分配記憶體,將其擴充套件到**newsize**。

動態分配記憶體

在程式設計中,如果您知道陣列的大小,那麼很容易定義它為一個數組。例如,要儲存任何人的姓名,最多可以達到100個字元,因此您可以定義如下內容:

char name[100];

但是,現在讓我們考慮一種情況,您不知道需要儲存文字的長度,例如,您想儲存關於某個主題的詳細說明。在這裡,我們需要定義一個指向字元的指標,而不定義需要多少記憶體,稍後,根據需要,我們可以分配記憶體,如下例所示:

示例程式碼

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
   char name[100];
   char *description;
   strcpy(name, "Adam");
   /* allocate memory dynamically */
   description = malloc( 200 * sizeof(char) );
   if( description == NULL ) {
      fprintf(stderr, "Error - unable to allocate required memory
");    } else {       strcpy( description, "Adam a DPS student in class 10th");    }    printf("Name = %s
", name );    printf("Description: %s
", description ); }

輸出

Name = Zara Ali
Description: Zara ali a DPS student in class 10th

可以使用calloc()編寫相同的程式;唯一需要做的就是將malloc替換為calloc,如下所示:

calloc(200, sizeof(char));

因此,您可以完全控制,並且在分配記憶體時可以傳遞任何大小的值,這與陣列不同,陣列一旦定義了大小,就不能更改。

調整記憶體位置大小

當您的程式退出時,作業系統會自動釋放程式分配的所有記憶體,但作為一種良好的實踐,當您不再需要記憶體時,應該透過呼叫free()函式來釋放該記憶體。

或者,您可以透過呼叫realloc()函式來增加或減小已分配記憶體塊的大小。讓我們再次檢查上面的程式,並使用realloc()和free()函式:

示例程式碼

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
   char name[100];
   char *description;
   strcpy(name, "Adam");
   /* allocate memory dynamically */
   description = malloc( 30 * sizeof(char) );
   if( description == NULL ) {
      fprintf(stderr, "Error - unable to allocate required memory
");    } else {       strcpy( description, "Adam a DPS student.");    }    /* suppose you want to store bigger description */    description = realloc( description, 100 * sizeof(char) );    if( description == NULL ) {       fprintf(stderr, "Error - unable to allocate required memory
");    } else {       strcat( description, "He is in class 10th");    }    printf("Name = %s
", name );    printf("Description: %s
", description );    /* release memory using free() function */    free(description); }

輸出

Name = Adam
Description: Adam a DPS student.He is in class 10th

您可以嘗試在不重新分配額外記憶體的情況下執行上述示例,由於description中可用記憶體不足,strcat()函式將報錯。

更新於:2019年7月30日

2K+ 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.