free() เป็นฟังก์ชันใน C Standard Library (<cstdlib> / <stdlib.h>) ใช้สำหรับ Deallocate (ปล่อย) หน่วยความจำที่จองไว้ด้วย malloc(), calloc(), หรือ realloc() เท่านั้น
ลายเซ็น
void free(void* ptr);
ptr: Pointer ที่ได้จากmalloc/calloc/realloc- ถ้า
ptr == nullptr: ไม่ทำอะไร (Safe) - ไม่คืนค่า (void)
ตัวอย่างครบวงจร: malloc → realloc → free
#include <iostream>
#include <cstdlib>
#include <cstring>
int main() {
// 1. Allocate
char* str = static_cast<char*>(std::malloc(15)); // 15 bytes
if (!str) return 1; // Check NULL
std::strcpy(str, "tutorialspoint");
std::cout << "String = " << str << ", Address = " << static_cast<void*>(str) << '\n';
// 2. Reallocate (ขยายขนาด)
str = static_cast<char*>(std::realloc(str, 25)); // 25 bytes
if (!str) return 1;
std::strcat(str, ".com");
std::cout << "String = " << str << ", Address = " << static_cast<void*>(str) << '\n';
// 3. Deallocate (สำคัญมาก!)
std::free(str);
str = nullptr; // Good Practice: ป้องกัน Dangling Pointer
return 0;
}
ผลลัพธ์
String = tutorialspoint, Address = 0x22fe38
String = tutorialspoint.com, Address = 0x22fe38
กฎสำคัญ (Rules of Thumb)
| กฎ | รายละเอียด |
|---|---|
| จับคู่ new/delete | new → delete, new[] → delete[] |
| จับคู่ malloc/free | malloc/calloc/realloc → free |
| ห้ามผสม | ห้าม free(new_ptr) หรือ delete(malloc_ptr) → Undefined Behavior |
| Free NULL ปลอดภัย | free(nullptr) เป็น No-op (ปลอดภัย) |
| Double Free | Free เดียวกัน 2 ครั้ง → Heap Corruption / Crash |
| Use After Free | Access Memory หลัง Free → Undefined Behavior |
| Memory Leak | ไม่ Free → Memory หายไปจนจบ Process |
C++ Modern Approach: Smart Pointers (หลีกเลี่ยง free/delete โดยตรง)
#include <memory>
#include <iostream>
int main() {
// Unique Ownership
auto ptr = std::make_unique<int[]>(100); // auto free ด้วย delete[]
// Shared Ownership
auto shared = std::make_shared<std::string>("Hello");
// Custom Deleter สำหรับ C API (malloc/free)
auto c_ptr = std::unique_ptr<char, decltype(&std::free)>(
static_cast<char*>(std::malloc(100)), std::free
);
}
สรุป
free() เป็น C-style Memory Deallocation สำหรับ malloc/calloc/realloc ใน C++ สูงสุดควรใช้ Smart Pointers (unique_ptr, shared_ptr) พร้อม Custom Deleter เพื่อ RAII (Resource Acquisition Is Initialization) ป้องกัน Memory Leak และ Double Free โดยอัตโนมัติ