Pointer และหน่วยความจำ

การจัดการ Dynamic Memory

Dynamic storage ใช้เมื่อ size หรือ lifetime ไม่ทราบตอน compile

การจัดการ Dynamic Memory คืออะไร?

Dynamic storage ใช้เมื่อ size หรือ lifetime ไม่ทราบตอน compile

Allocate array ตอน runtime และ release อย่างปลอดภัย

ประเด็นสำคัญ

  • Pointer ต้องชี้ object ที่ยังมีชีวิตและ type ตรงกันหรือเป็น null
  • Allocation ที่เป็นเจ้าของต้องถูก free เพียงครั้งเดียว
  • ระบุ ownership และ const ให้ชัดเจน

ตัวอย่างโค้ด C และ C++

C
รันโค้ด →
main.c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t count = 5;
    int *values = calloc(count, sizeof *values);
    if (!values) return 1;
    for (size_t i = 0; i < count; ++i) values[i] = (int)(i * i);
    printf("last=%d\n", values[count - 1]);
    free(values);
    return 0;
}
ผลลัพธ์ที่คาดหวัง
last=16
C++
รันโค้ด →
main.cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> values(5);
    for (std::size_t i = 0; i < values.size(); ++i) values[i] = static_cast<int>(i * i);
    std::cout << "last=" << values.back() << '\n';
}
ผลลัพธ์ที่คาดหวัง
last=16

เปรียบเทียบ C และ C++

C ต้องจับคู่ malloc/calloc กับ free และตรวจ failure ส่วน std::vector เป็นเจ้าของและปล่อย memory อัตโนมัติแม้เกิด exception

C

Ownership และ cleanup เป็นกฎที่โปรแกรมเมอร์ต้องดูแล

C++

Container และ RAII ผูก ownership กับ lifetime ของ object

แบบฝึกหัด

รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา

  • ทดสอบ null และ allocation failure
  • ใช้ AddressSanitizer และ UndefinedBehaviorSanitizer
  • บันทึก ownership ของ pointer ทุกตัว