C undefined behavior — สิ่งที่ต้องกลัวที่สุด



undefined behavior (UB) = โค้ดที่มาตรฐาน C บอกว่า “ไม่กำหนดว่าจะเกิดอะไร” — คอมไพเลอร์ทำอะไรก็ได้: รันปกติ, crash, คืนค่าผิด, ลบโค้ดทิ้ง, หรือช่องโหว่ความปลอดภัย

ทำไม UB อันตรายกว่าที่คิด

คอมไพเลอร์ สมมติว่า UB ไม่มีทางเกิด แล้วปรับแต่งโค้ดตามสมมติฐานนั้น:

int foo(int *p)
{
    int x = *p;              // ถ้า p เป็น NULL นี่คือ UB
    if (p == NULL) {         // คอมไพเลอร์: "ถ้า p เป็น NULL บรรทัดบนจะ UB
        return -1;           //  ดังนั้น p ต้องไม่เป็น NULL — ลบ if นี้ทิ้งได้!"
    }
    return x + 1;
}

โค้ดที่ optimize แล้วอาจ ไม่มีการเช็ค NULL เลย เพราะคอมไพเลอร์ “พิสูจน์” ว่ามันไม่จำเป็น — จากการมี UB อยู่ข้างบน นี่คือเหตุที่ “โปรแกรมรันได้ = ไม่มีบั๊ก” เป็นความเชื่อผิด — UB อาจไม่แสดงอาการจนเปลี่ยน -O2, เปลี่ยน compiler, หรือเปลี่ยน input

UB ที่พบบ่อย

1. อ่านตัวแปร/หน่วยความจำที่ยังไม่ init

int x;
printf("%d\n", x);           // UB
int *arr = malloc(10 * sizeof(int));
int y = arr[0];              // UB — malloc ไม่ล้าง

2. เข้าถึงอาร์เรย์นอกขอบเขต

int a[5];
a[5] = 1;                    // UB (index 0-4)
a[-1] = 0;                   // UB
int *p = a + 10;             // UB — แค่คำนวณก็ผิด (ไม่ต้อง deref)

3. dereference NULL หรือ dangling pointer

int *p = NULL;
*p = 5;                      // UB (มัก segfault แต่ไม่รับประกัน)

int *q = malloc(4);
free(q);
*q = 5;                      // UB — use after free

4. signed integer overflow

int x = INT_MAX;
int y = x + 1;               // UB (unsigned overflow ไม่ใช่ UB — วน modulo)
int z = INT_MIN / -1;        // UB (ผลเกิน INT_MAX)
int w = 1 << 31;             // UB (shift signed เกินขอบ)

5. หาร/mod ด้วย 0

int a = 10 / 0;              // UB
int b = 10 % 0;              // UB

6. แก้ตัวแปรเดียวหลายครั้งในนิพจน์เดียว (ไม่มี sequence point)

int i = 0;
i = i++ + ++i;               // UB
arr[i] = i++;                // UB
printf("%d %d\n", i++, i++); // UB

7. shift มากเกินหรือติดลบ

int x = 1 << 40;             // UB (40 >= จำนวนบิตของ int)
int y = 1 << -1;             // UB

8. type punning ผิดกฎ (strict aliasing)

float f = 3.14f;
int *p = (int *)&f;          // เข้าถึง float ผ่าน int* — UB (strict aliasing violation)
int bits = *p;
// ทางที่ถูก:
int bits;
memcpy(&bits, &f, sizeof(bits));

9. สตริงไม่ปิด '\0' / buffer overflow

char buf[3];
strcpy(buf, "hello");        // UB — เขียนเกิน
char c = 'A';
strlen(&c);                  // UB — ไม่มี '\0'

10. ลืม return ในฟังก์ชันที่คืนค่า

int get_value(int x)
{
    if (x > 0) return x;
    // ไม่มี return ถ้า x <= 0 — ผู้เรียกได้ UB
}

unspecified / implementation-defined ต่างจาก UB

  • implementation-defined — คอมไพเลอร์เลือกได้ แต่ต้องบอกไว้ในเอกสาร และสม่ำเสมอ (เช่น char เป็น signed หรือ unsigned, >> ของ signed)
  • unspecified — ผลลัพธ์ที่เป็นไปได้มีจำกัด แต่ไม่ระบุอันไหน (เช่น ลำดับการประเมิน argument ของฟังก์ชัน)
  • undefined — อะไรก็เกิดได้ ไม่มีการรับประกันใด ๆ

พยายามหลีกเลี่ยงทั้งสามในโค้ด portable แต่ UB คือตัวที่อันตรายที่สุด

จับ UB ด้วย UndefinedBehaviorSanitizer

gcc -std=c17 -g -fsanitize=undefined ub.c -o ub
./ub
// ub.c
#include <limits.h>
int main(void) {
    int x = INT_MAX;
    return x + 1;             // overflow
}
ub.c:4:14: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'

UBSan จับ: overflow, shift ผิด, null deref, array OOB (บางกรณี), misaligned access, division by zero — ใช้คู่กับ ASan ทุกครั้งตอน dev/test:

gcc -std=c17 -Wall -Wextra -g -fsanitize=address,undefined prog.c -o prog

warning ที่ช่วยเตือน UB ล่วงหน้า

gcc -Wall -Wextra -Wpedantic \
    -Wshadow -Wconversion -Wsign-conversion \
    -Wcast-qual -Wnull-dereference \
    prog.c -o prog

-Wall -Wextra จับได้เยอะ: uninitialized, return ที่ขาด, comparison ผิด, fallthrough

นิสัยที่ลด UB

  • init ตัวแปรทุกตัว, เช็ค pointer != NULL ก่อน deref, p = NULL หลัง free
  • เช็คขอบเขตก่อน index อาร์เรย์
  • ใช้ unsigned เมื่อทำ bit manipulation / shift
  • เช็ค overflow ก่อนบวก/คูณค่าจาก input (<limits.h>)
  • ไม่แก้ตัวแปรเดียวหลายครั้งในนิพจน์เดียว
  • memcpy แทน type punning ผ่าน pointer cast
  • snprintf แทน sprintf/strcpy
  • -fsanitize=address,undefined + -Wall -Wextra เสมอ

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

  • “โปรแกรมรันได้ = ไม่มี UB” — UB อาจซ่อนจนเปลี่ยน compiler/optimization/input รัน sanitizer เสมอ
  • คิดว่า signed overflow “จะวน” — เป็น UB, คอมไพเลอร์อาจ optimize x + 1 > x เป็น true เสมอ
  • cast pointer ข้ามชนิดเพื่อ “ดูบิต” — strict aliasing UB, ใช้ memcpy หรือ union (บางกรณี)
  • แก้ warning ด้วยการ cast ให้เงียบ — ซ่อนบั๊กจริง เข้าใจ warning ก่อน
  • ปิด UBSan เพราะ “โค้ดมันทำงานได้” — error จริง

สรุป

  • UB = มาตรฐานไม่กำหนดผล คอมไพเลอร์สมมติว่าไม่เกิดและ optimize ตามนั้น → อาการไม่แน่นอน
  • ที่พบบ่อย: uninitialized read, OOB array, null/dangling deref, signed overflow, div by 0, แก้ตัวแปรซ้ำในนิพจน์เดียว, shift เกินขอบ, strict aliasing, buffer overflow, return ที่ขาด
  • ต่างจาก implementation-defined (บอกไว้) และ unspecified (จำกัดตัวเลือก)
  • -fsanitize=address,undefined + -Wall -Wextra ทุกครั้งตอน dev/test
  • แก้ต้นตอ ไม่ปิด sanitizer/warning

บทถัดไปว่าด้วย const correctness, restrict และ volatile — เครื่องมือบอกเจตนาให้คอมไพเลอร์และผู้อ่าน