ฟังก์ชันไลบรารี 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