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

Dynamic Memory Allocation ใน C ตอนที่ 2: หาผลรวม N จำนวน


โจทย์

หาผลรวมของ N จำนวนที่ User ป้อน โดยใช้ Dynamic Memory Allocation

ฟังก์ชันหลัก

  • malloc() - จอง Memory Block
  • calloc() - จอง Memory แบบ Contiguous + Zero Init
  • realloc() - ปรับขนาด Memory
  • free() - ปล่อย Memory

ตัวอย่างโปรแกรม: หาผลรวม + Demo free()

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

int main() {
    int n, *p, i, sum = 0;
    
    printf("Enter number of elements: ");
    scanf("%d", &n);
    
    // จอง Memory
    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);
        sum += *(p + i);
    }
    
    printf("Sum of elements: %d\n", sum);
    
    // Demo: free() แล้วลองอ่านอีก (จะได้ Garbage)
    free(p);
    printf("\nAfter free() - Reading freed memory (Garbage):\n");
    for (i = 0; i < n; i++)
        printf("%d\n", p[i]); // Undefined Behavior!
    
    return 0;
}

ผลลัพธ์ตัวอย่าง:


Enter number of elements: 5
Enter 5 elements:
23 34 12 34 56
Sum of elements: 159

After free() - Reading freed memory (Garbage):
12522624
0
12517712
0
56

⚠️ ข้อควรระวังจากตัวอย่าง

อย่า Access Memory หลัง free()! โค้ดส่วนท้ายเป็นเพื่อ Demo เท่านั้น การอ่าน p[i] หลัง free(p) เป็น **Undefined Behavior** อาจ Crash ได้

การใช้ calloc() แทน malloc()


// calloc: จอง n elements ขนาด size, init เป็น 0
int *p = (int *)calloc(n, sizeof(int));
// เทียบเท่า:
int *p = (int *)malloc(n * sizeof(int));
memset(p, 0, n * sizeof(int));

การใช้ realloc()


// ขยาย Array จาก 5 เป็น 10 elements
p = (int *)realloc(p, 10 * sizeof(int));
if (p == NULL) { /* Handle error */ }
// ข้อมูลเดิม 5 ตัวแรกยังคงอยู่

สรุปการเลือกใช้

FunctionUse Case
mallocจอง Memory ทั่วไป ไม่ต้องการ Init
callocจอง Memory + ต้องการค่าเริ่มต้น 0
reallocResize Array ที่จองไว้ (ขยาย/ลด)
freeปล่อย Memory (บังคับต้องมีคู่กับ malloc/calloc/realloc)