C++中的自由函式是什麼?


C/C++庫函式void free(void *ptr)釋放先前由對calloc、malloc或realloc的呼叫分配的記憶體。以下是free()函式的宣告。

void free(void *ptr)

此函式採用一個指標ptr。這是之前透過malloc、calloc或realloc分配的記憶體塊的指標,該記憶體塊將被釋放。如果傳遞一個空指標為引數,則不執行任何操作。

示例

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main () {
   char *str;
   /* Initial memory allocation */
   str = (char *) malloc(15);
   strcpy(str, "tutorialspoint");
   cout << "String = "<< str <<", Address = "<< &str << endl;
   /* Reallocating memory */
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
   cout << "String = "<< str <<", Address = "<< &str << endl;
   /* Deallocate allocated memory */
   free(str);
   return(0);
}

輸出

String = tutorialspoint, Address = 0x22fe38
String = tutorialspoint.com, Address = 0x22fe38

更新日期:2019-07-30

300次瀏覽

職業生涯起航

完成課程以獲得認證

開始
廣告
© . All rights reserved.