C บั๊กหน่วยความจำและวิธีจับ



บั๊กหน่วยความจำเป็นสาเหตุของช่องโหว่ความปลอดภัยส่วนใหญ่ในซอฟต์แวร์ C/C++ ตลอด 30 ปี รู้จักแต่ละแบบและมีเครื่องมือจับ

1. use-after-free

ใช้ pointer หลังจาก free แล้ว:

int *p = malloc(sizeof(int));
*p = 42;
free(p);
printf("%d\n", *p);       // ❌ UB — หน่วยความจำถูกคืนแล้ว อาจถูกจองใหม่ให้ของอื่น

แก้: ตั้ง p = NULL หลัง free — deref NULL บนระบบทั่วไปมัก crash ทันที (debug ง่ายกว่าค่าขยะ; มาตรฐานถือเป็น UB ไม่การันตีว่า crash)

free(p);
p = NULL;
// printf("%d\n", *p);    // ตอนนี้มัก crash ทันที ชัดเจน

ระวัง: ตั้ง p = NULL แก้ได้เฉพาะ pointer ตัวนั้น — ถ้ามี pointer ตัวอื่น (alias) ที่ยังชี้ก้อนที่ free ไปแล้ว มันยังเป็น use-after-free อยู่ ต้องออกแบบว่าใครเป็น “เจ้าของ” ก้อนนั้น

2. double free

int *p = malloc(sizeof(int));
free(p);
free(p);                  // ❌ UB — คืนบล็อกเดิมสองครั้ง ทำลาย heap metadata

แก้: p = NULL หลัง free — free(NULL) ปลอดภัย ไม่ทำอะไร

3. memory leak

จองแล้วไม่คืน — ต่างจากบั๊กอื่นในบทนี้ตรงที่ leak ไม่ใช่ undefined behavior ตัวมันเอง โปรแกรมยังทำงานถูกต้อง แต่กินหน่วยความจำเพิ่มเรื่อย ๆ จนอาจหมด (สำคัญมากในโปรแกรมที่รันยาว เช่น server, daemon):

void process(void)
{
    char *buf = malloc(1024);
    if (some_error()) {
        return;           // ❌ ลืม free(buf) — leak 1 KB ทุกครั้งที่ error
    }
    // ...
    free(buf);
}

แก้: free ทุก exit path — ใช้ goto cleanup (บทที่ 32):

void process(void)
{
    char *buf = malloc(1024);
    if (!buf) return;

    if (some_error()) {
        goto cleanup;
    }
    // ... ทำงาน

cleanup:
    free(buf);
}

4. buffer overflow / over-read

เขียนหรืออ่านนอกขอบเขตที่จอง:

int *arr = malloc(5 * sizeof(int));
arr[5] = 10;              // ❌ เขียน index 5 (มีแค่ 0-4) — เขียนทับ heap metadata
arr[-1] = 0;              // ❌ เขียนก่อนบล็อก

char buf[10];
strcpy(buf, "This string is way too long");   // ❌ เขียนทะลุ stack

buffer overflow บน stack คือช่องโหว่ “stack smashing” ที่ใช้ยึดเครื่องได้ (เขียนทับ return address)

5. dangling pointer — คืน pointer ไปตัวแปร local

char *make_greeting(const char *name)
{
    char buf[100];
    snprintf(buf, sizeof(buf), "สวัสดี %s", name);
    return buf;            // ❌ buf อยู่บน stack — หายเมื่อฟังก์ชัน return
}

int main(void)
{
    char *g = make_greeting("อร");
    printf("%s\n", g);     // ❌ อ่านหน่วยความจำที่ไม่ valid แล้ว
}

แก้: ให้ผู้เรียกส่ง buffer มา หรือ malloc แล้วให้ผู้เรียก free:

// วิธี A: ผู้เรียกให้ buffer
void make_greeting(char *out, size_t size, const char *name)
{
    snprintf(out, size, "สวัสดี %s", name);
}

// วิธี B: malloc แล้วผู้เรียก free
char *make_greeting(const char *name)
{
    char *buf = malloc(100);
    if (buf) snprintf(buf, 100, "สวัสดี %s", name);
    return buf;            // ผู้เรียกต้อง free
}

6. อ่าน uninitialized memory

int *arr = malloc(5 * sizeof(int));
printf("%d\n", arr[0]);   // ❌ ค่าขยะ — malloc ไม่ล้าง (ใช้ calloc ถ้าต้องการ 0)

เครื่องมือ 1: AddressSanitizer (ASan)

คอมไพล์ด้วย -fsanitize=address — โปรแกรมจะตรวจทุกการเข้าถึงหน่วยความจำตอนรัน:

gcc -std=c17 -g -fsanitize=address,undefined bug.c -o bug
./bug
// bug.c
#include <stdlib.h>
int main(void) {
    int *p = malloc(5 * sizeof(int));
    p[5] = 1;             // เขียนเกิน
    free(p);
    return 0;
}
==12345==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x...
WRITE of size 4 at 0x... thread T0
    #0 0x... in main bug.c:5          ← p[5] = 1;
    ...
0x... is located 0 bytes to the right of 20-byte region
allocated by thread T0 here:
    #0 0x... in malloc
    #1 0x... in main bug.c:4          ← malloc(5 * sizeof(int))

(เลขบรรทัด/ที่อยู่เป็นตัวอย่าง — ของจริงขึ้นกับ source และระบบ)

ASan บอก บรรทัดที่พลาด และ บรรทัดที่ malloc — แม่นมาก ใช้ตอน dev และ CI เสมอ (ช้าลง ~2 เท่า ไม่ใช้ใน production build)

เครื่องมือ 2: valgrind

ไม่ต้องคอมไพล์พิเศษ (แค่ -g):

gcc -g bug.c -o bug
valgrind --leak-check=full ./bug
==12345== Invalid write of size 4
==12345==    at 0x...: main (bug.c:5)
==12345==  Address 0x... is 0 bytes after a block of size 20 alloc'd
...
==12345== All heap blocks were freed -- no leaks are possible

bug.c ตัวนี้ free(p) ครบ — valgrind จึงรายงานแค่ Invalid write (เขียนเกินขอบ) ไม่มี leak ถ้าลบ free(p) ออก จะเห็น LEAK SUMMARY: definitely lost: 20 bytes เพิ่มมา valgrind จับ leak ได้ดีมาก ช้ากว่า ASan (~10-20 เท่า) ใช้เมื่อ ASan ไม่พอ หรือบนโค้ดที่ compile ใหม่ไม่ได้

นิสัยที่ลดบั๊ก

  • p = NULL หลัง free(p) ทุกครั้ง
  • calloc แทน malloc เมื่อต้องการเนื้อเป็น 0
  • จับคู่ malloc/free ในฟังก์ชันเดียวกัน ถ้าทำได้ (create/destroy pattern ถ้าไม่ได้)
  • goto cleanup สำหรับฟังก์ชันที่จองหลายอย่าง
  • เช็ค NULL หลัง malloc เสมอ
  • -fsanitize=address,undefined ตอน dev + CI
  • snprintf ไม่ใช่ sprintf/strcpy ดิบ
  • คิดเรื่อง “ใครเป็นเจ้าของ (owns) หน่วยความจำนี้ ใครมีหน้าที่ free” ทุกครั้งที่เขียน pointer

เรื่องที่คนมักพลาด

  • “โปรแกรมรันได้ปกติ = ไม่มีบั๊กหน่วยความจำ” — UB อาจไม่แสดงอาการจนกว่าจะเปลี่ยนคอมไพเลอร์/OS/ขนาด input รัน ASan เสมอ
  • ทดสอบเฉพาะ happy path — leak มักซ่อนใน error path ทดสอบกรณี error ด้วย
  • ไม่รัน valgrind/ASan เพราะ “ช้า” — ใช้เฉพาะตอน dev/test ไม่ใช่ production
  • free แล้วลืม set NULL — บั๊กถัดไปจะเป็น use-after-free ที่หายาก
  • แก้ ASan error ด้วยการปิด ASan — error จริง ต้องแก้ต้นตอ

สรุป

  • บั๊กหลัก: use-after-free, double free, buffer overflow, dangling pointer, uninitialized read — เป็น UB; memory leak ไม่ใช่ UB แต่เป็นบั๊กที่ทำให้หน่วยความจำหมด
  • p = NULL หลัง free ลด use-after-free / double free ผ่าน pointer ตัวนั้น — แต่ไม่ช่วย alias ตัวอื่น ต้องชัดเรื่อง ownership
  • อย่าคืน pointer ไปตัวแปร local — ให้ผู้เรียกส่ง buffer มา หรือ malloc แล้วให้ผู้เรียก free
  • AddressSanitizer (-fsanitize=address) — เร็ว แม่น บอกบรรทัด ใช้ตอน dev + CI เสมอ
  • valgrind — จับ leak ดี ไม่ต้อง compile พิเศษ ช้ากว่า
  • คิดเรื่อง “ownership” ของทุก pointer

บทถัดไปว่าด้วยอาร์เรย์หลายมิติและ array of pointers — int m[3][4], char *argv[], jagged array