ความหมาย
malloc() จัดสรรหน่วยความจำขนาดที่ระบุ (bytes) และคืน pointer ไปยังจุดเริ่มต้น ไม่ initialize ค่า (garbage)
Prototype
void *malloc(size_t size);
Syntax
ptr = (cast*) malloc(size_in_bytes);
ตัวอย่าง
int *ptr; ptr = (int*) malloc(1000); // 1000 bytes ptr = (int*) malloc(n * sizeof(int)); // n integers
หมายเหตุ: คืน NULL หากหน่วยความจำไม่พอ
ตัวอย่างโปรแกรมที่ 1: สร้าง Array แบบไดนามิก
#include <stdio.h>
#include <stdlib.h>
int main() {
int numofele, i;
int *p;
printf("ป้อนจำนวน elements: ");
scanf("%d", &numofele);
p = (int*) malloc(numofele * sizeof(int));
if (p == NULL) {
printf("หน่วยความจำไม่พอ\\n");
return 1;
}
for (i = 0; i < numofele; i++) {
p[i] = i + 1;
printf("Element %d = %d\\n", i, p[i]);
}
free(p);
return 0;
}ผลลัพธ์
ป้อนจำนวน elements: 4 Element 0 = 1 Element 1 = 2 Element 2 = 3 Element 3 = 4
ตัวอย่างโปรแกรมที่ 2: หาผลรวมและ Free หน่วยความจำ
#include <stdio.h>
#include <stdlib.h>
int main() {
int numofe, i, sum = 0;
int *p;
printf("ป้อนจำนวน elements: ");
scanf("%d", &numofe);
p = (int*) malloc(numofe * sizeof(int));
if (p == NULL) {
printf("หน่วยความจำไม่พอ\\n");
return 1;
}
printf("ป้อนตัวเลข:\\n");
for (i = 0; i < numofe; i++) {
scanf("%d", p + i);
sum += *(p + i);
}
printf("ผลรวม = %d\\n", sum);
free(p); // คืนหน่วยความจำ
printf("\\nหลัง free() ค่าใน array (garbage):\\n");
for (i = 0; i < numofe; i++) {
printf("%d\\n", p[i]); // Undefined behavior! เข้าถึงหลัง free
}
return 0;
}ผลลัพธ์ตัวอย่าง
ป้อนจำนวน elements: 5 ป้อนตัวเลข: 12 10 24 45 67 ผลรวม = 158 หลัง free() ค่าใน array (garbage): 7804032 0 7799120 0 67
คำเตือน: การเข้าถึง p[i] หลัง free(p) เป็น Undefined Behavior ผลลัพธ์ไม่แน่นอน อาจ crash ได้
Best Practices
- ตรวจสอบ NULL หลัง malloc เสมอ
- free() ทุกครั้งที่ malloc/calloc/realloc
- ตั้งค่า pointer = NULL หลัง free ป้องกัน double free
- ใช้ calloc ถ้าต้องการค่าเริ่มต้นเป็น 0
- คำนวณ size ด้วย
n * sizeof(type)ป้องกันผิดพลาด