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

Realloc ในภาษา C

ความหมาย

realloc() ใช้ปรับขนาดหน่วยความจำที่จัดสรรไว้ก่อนหน้าด้วย malloc หรือ calloc สามารถเพิ่มหรือลดขนาดได้

Prototype

void *realloc(void *ptr, size_t new_size);

พารามิเตอร์

  • ptr - pointer ที่ได้จาก malloc/calloc/realloc ก่อนหน้า (หรือ NULL)
  • new_size - ขนาดใหม่ในหน่วยไบต์

คืนค่า

  • Pointer ไปยังหน่วยความจำที่ปรับขนาดแล้ว (อาจเปลี่ยน address ได้)
  • NULL หากจัดสรรล้มเหลว (ข้อมูลเดิมยังคงอยู่ไม่สูญหาย)

ฟังก์ชันจัดสรรหน่วยความจำ Dynamic

ฟังก์ชันวัตถุประสงค์
malloc(size)จัดสรรหน่วยความจำ size ไบต์ (ไม่ initialize)
calloc(n, size)จัดสรร n บล็อก ขนาด size ไบต์ (initialize เป็น 0)
realloc(ptr, new_size)ปรับขนาดหน่วยความจำที่ ptr ชี้อยู่
free(ptr)คืนหน่วยความจำ

ตัวอย่างการใช้งาน

int *ptr;
ptr = (int*) malloc(1000);      // จัดสรร 1000 bytes
ptr = (int*) realloc(ptr, 500); // ลดเหลือ 500 bytes
ptr = (int*) realloc(ptr, 1500); // เพิ่มเป็น 1500 bytes

ตัวอย่างโปรแกรม: ปรับขนาด Array แบบไดนามิก

#include <stdio.h>
#include <stdlib.h>
int main() {
    int *ptr, i, num;
    printf("ขนาด array เริ่มต้น: 5\\n");
    ptr = (int*) calloc(5, sizeof(int));
    if (ptr == NULL) {
        printf("จัดสรรหน่วยความจำล้มเหลว\\n");
        return 1;
    }
    for (i = 0; i < 5; i++) {
        printf("ป้อนตัวเลข index %d: ", i);
        scanf("%d", ptr + i);
    }
    printf("\\nเพิ่มขนาด array เป็น 7\\n");
    ptr = (int*) realloc(ptr, 7 * sizeof(int));
    if (ptr == NULL) {
        printf("จัดสรรหน่วยความจำล้มเหลว\\n");
        return 1;
    }
    printf("\\nป้อนตัวเลขเพิ่มอีก 2 ตัว:\\n");
    for (i = 5; i < 7; i++) {
        printf("ป้อนตัวเลข index %d: ", i);
        scanf("%d", ptr + i);
    }
    printf("\\nArray ผลลัพธ์:\\n");
    for (i = 0; i < 7; i++) {
        printf("%d ", *(ptr + i));
    }
    printf("\\n");
    free(ptr);
    return 0;
}

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

ขนาด array เริ่มต้น: 5
ป้อนตัวเลข index 0: 23
ป้อนตัวเลข index 1: 12
ป้อนตัวเลข index 2: 45
ป้อนตัวเลข index 3: 67
ป้อนตัวเลข index 4: 20
เพิ่มขนาด array เป็น 7
ป้อนตัวเลขเพิ่มอีก 2 ตัว:
ป้อนตัวเลข index 5: 90
ป้อนตัวเลข index 6: 60
Array ผลลัพธ์:
23 12 45 67 20 90 60

ข้อควรระวังสำคัญ

  • Pointer อาจเปลี่ยน: realloc อาจย้ายหน่วยความจำไปที่ใหม่ ต้องเก็บค่าคืนมาในตัวแปรเดิมเสมอ
  • ตรวจสอบ NULL: หาก realloc ล้มเหลว จะคืน NULL แต่หน่วยความจำเดิมยังคงอยู่ (ไม่สูญหาย)
  • ข้อมูลเดิมคงอยู่: ข้อมูลในส่วนที่ทับซ้อนจะคงเดิม ส่วนที่เพิ่มมาใหม่จะมีค่า indeterminate (ถ้า malloc) หรือ 0 (ถ้า calloc เดิม)
  • realloc(ptr, 0) เทียบเท่า free(ptr) (implementation-defined)

Best Practice

// ปลอดภัย: ใช้ temporary pointer
void *temp = realloc(ptr, new_size);
if (temp != NULL) {
    ptr = temp;
} else {
    // handle error, ptr ยังชี้ไปที่ข้อมูลเดิม
}