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

การทำงานของ malloc() และ free() ใน C/C++

malloc()

จองหน่วยความจำตามขนาดไบต์ที่ระบุ ส่งคืน Pointer ไปยังไบต์แรก ส่งคืน NULL หากล้มเหลว

รูปแบบ

pointer_name = (cast_type*) malloc(size_in_bytes);

ตัวอย่าง

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

int main() {
    int n = 4, i, *p, s = 0;
    p = (int*) malloc(n * sizeof(int));
    if (p == NULL) {
        printf("\nError! memory not allocated.");
        exit(0);
    }
    printf("\nEnter elements of array : ");
    for (i = 0; i < n; ++i) {
        scanf("%d", p + i);
        s += *(p + i);
    }
    printf("\nSum : %d", s);
    return 0;
}

free()

ปล่อยหน่วยความจำที่จองด้วย malloc() ไม่เปลี่ยนค่าพอยน์เตอร์ (ยังชี้ตำแหน่งเดิม ต้องตั้งค่า NULL เอง)

รูปแบบ

void free(void *pointer_name);

ตัวอย่าง (รวม free)

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

int main() {
    int n = 4, i, *p, s = 0;
    p = (int*) malloc(n * sizeof(int));
    if (p == NULL) {
        printf("\nError! memory not allocated.");
        exit(0);
    }
    printf("\nEnter elements of array : ");
    for (i = 0; i < n; ++i) {
        scanf("%d", p + i);
        s += *(p + i);
    }
    printf("\nSum : %d", s);
    free(p);
    return 0;
}

ข้อสังเกตสำคัญ

  • ต้อง free() ทุกครั้งที่ malloc() สำเร็จ (ป้องกัน Memory Leak)
  • หลัง free() ควรตั้ง ptr = NULL (ป้องกัน Dangling Pointer)
  • ใน C++ ควรใช้ new/delete แทน (เรียก Constructor/Destructor)