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

Pointer และ Address

Pointer เก็บ address ของ object ที่มี type เข้ากันได้

Pointer และ Address คืออะไร?

Pointer เก็บ address ของ object ที่มี type เข้ากันได้

เก็บ address, dereference และแก้ object ต้นฉบับ

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

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

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

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

int main(void) {
    int score = 70;
    int *score_ptr = &score;
    *score_ptr += 5;
    printf("score=%d same-address=%s\n", score,
           score_ptr == &score ? "yes" : "no");
    return 0;
}
ผลลัพธ์ที่คาดหวัง
score=75 same-address=yes
C++
รันโค้ด →
main.cpp
#include <iostream>

int main() {
    int score = 70;
    int* score_ptr = &score;
    *score_ptr += 5;
    std::cout << "score=" << score << " same-address="
              << std::boolalpha << (score_ptr == &score) << '\n';
}
ผลลัพธ์ที่คาดหวัง
score=75 same-address=true

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

C ใช้ raw pointer โดยตรง C++ ยังใช้สำหรับ non-owning access แต่ใช้ reference เมื่อ null ไม่มีความหมาย

C

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

C++

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

แบบฝึกหัด

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

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