Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Dynamic Memory Allocation ในภาษา C คืออะไร?


Dynamic Memory Allocation (การจัดสรรหน่วยความจำแบบไดนามิก)

การจองหน่วยความจำ **ระหว่างรันโปรแกรม (Runtime)** ไม่ใช่ตอน Compile Time

ฟังก์ชันหลัก (ใน <stdlib.h>)

คุณสมบัติ

  • ใช้ **Heap** สำหรับเก็บข้อมูล
  • มี **Memory Reusability** - ปล่อยได้เมื่อไม่ใช้
  • มีประสิทธิภาพด้าน Memory สูง
  • Execution ช้ากว่า Static Allocation เล็กน้อย
  • สามารถปล่อย Memory ได้ทุกจุดในโปรแกรม

ตัวอย่าง: หาผลรวมเลขคู่/คี่ ด้วย Dynamic Memory

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n, *p, i, even = 0, odd = 0;
    
    printf("Enter number of elements: ");
    scanf("%d", &n);
    
    // จอง Memory: n * sizeof(int) ไบต์
    p = (int *)malloc(n * sizeof(int));
    
    // ตรวจสอบการจองสำเร็จ
    if (p == NULL) {
        printf("Memory not available\n");
        return 1;
    }
    
    // รับข้อมูล
    printf("Enter %d elements:\n", n);
    for (i = 0; i < n; i++)
        scanf("%d", p + i); // p+i เทียบเท่า &p[i]
    
    // คำนวณ
    for (i = 0; i < n; i++) {
        if (*(p + i) % 2 == 0)
            even += *(p + i);
        else
            odd += *(p + i);
    }
    
    printf("Sum of even numbers: %d\n", even);
    printf("Sum of odd numbers: %d\n", odd);
    
    free(p); // สำคัญ: ปล่อย Memory!
    return 0;
}

ผลลัพธ์:


Enter number of elements: 4
Enter 4 elements:
35 24 46 12
Sum of even numbers: 82
Sum of odd numbers: 35

Common Mistakes (ผิดบ่อย)

  • ❌ malloc(n) → ต้องคูณ sizeof(type)
  • ❌ ไม่เช็ค NULL หลัง malloc
  • ❌ ลืม free() → Memory Leak
  • ❌ free() สองครั้ง (Double Free)
  • ❌ ใช้ Pointer หลัง free() (Use After Free)

Best Practices

  1. Check NULL ทุกครั้งหลัง Allocate
  2. free() ทุกครั้งที่จอง (ทุก malloc ต้องมี free คู่)
  3. Set Pointer = NULL หลัง Free
  4. ใช้ calloc() เมื่อต้องการ Zero-initialized
  5. ใช้ Tool ตรวจสอบ: Valgrind, AddressSanitizer
Functionคำอธิบาย
malloc(size)จอง Memory ขนาด size ไบต์ คืน Pointer (ไม่ Initialize)
calloc(n, size)จอง n บล็อก ขนาด size ไบต์ **Initialize เป็น 0**
realloc(ptr, new_size)ปรับขนาด Memory ที่จองไว้ (ขยาย/ลด)
free(ptr)ปล่อย Memory คืนระบบ