---
id: c-memory-reallocate
title: "C Reallocate Memory"
category: "Programming_Language"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["realloc() function", "temporary pointer pattern", "C 메모리 재할당"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.87
created_at: 2026-07-04
updated_at: 2026-07-04
review_reason: ""
merge_history: []
tags: ["c", "programming-language", "w3schools", "memory-management", "realloc"]
raw_sources: ["https://www.w3schools.com/c/c_memory_reallocate.php"]
applied_in: []
github_commit: ""
---

# [[C Reallocate Memory]]

## 🎯 한 줄 통찰 (One-line insight)
`realloc()` may or may not move the data to a NEW address — it tries to resize in place first, but if it can't, it silently allocates elsewhere and returns the new address, which means the ORIGINAL address becomes immediately unsafe to use the moment reallocation succeeds at a different location, making it essential to always capture `realloc()`'s return value into a SEPARATE temporary pointer rather than overwriting the original variable directly (since a failed call returns NULL and would otherwise destroy the only reference to the still-valid original memory). [S1]

## 🧠 핵심 개념 (Core concepts)
- **`realloc(ptr, newSize)`** — resizes previously allocated memory while PRESERVING its existing contents; returns either the SAME address (if resized in place) or a NEW address (if it had to move the data). [S1]
- **Old address becomes invalid on move** — once `realloc()` returns a different address, the original address is no longer safe to use. [S1]
- **NULL on failure** — if reallocation fails, `realloc()` returns `NULL`, and (per the previous chapter) the ORIGINAL memory remains valid and allocated. [S1]
- **Temporary-pointer safety pattern** — assign `realloc()`'s result to a SEPARATE variable first, check it for `NULL`, and only then update the original pointer — directly overwriting the original pointer risks losing it if the call fails. [S1]

## 📖 세부 내용 (Details)
- Growing an allocation from 4 to 6 integers: `size = 4 * sizeof(*ptr1); ptr1 = malloc(size); size = 6 * sizeof(*ptr1); ptr2 = realloc(ptr1, size);`. [S1]
- Safe NULL-check pattern before committing the resized pointer: `ptr1 = malloc(4); ptr2 = realloc(ptr1, 8); if (ptr2 == NULL) { printf("Failed. Unable to resize memory"); } else { printf("Success..."); ptr1 = ptr2; }`. [S1]

## ⚖️ 모순 및 업데이트 (Contradictions & updates)
- **realloc 결과를 임시 포인터에 먼저 받아야 하는 이유**: realloc()이 실패하면 NULL을 반환하는데, 이를 원래 포인터 변수에 바로 대입해버리면 여전히 유효한 원본 메모리 주소를 잃어버리게 된다는 점이 명시적으로 경고됨. [S1]

## 🛠️ 적용 사례 (Applied in summary)
현재 발견된 실제 적용 사례가 없습니다 — 4개 정수에서 6개 정수로 메모리를 확장하는 예제가 실전에서 배열 크기를 동적으로 늘려야 할 때의 대표 패턴이다. [S1]

## 💻 코드 패턴 (Code patterns)
Safely resizing memory using a temporary pointer to avoid losing the original on failure (C):
```c
int *ptr1, *ptr2;
ptr1 = malloc(4);
ptr2 = realloc(ptr1, 8);
if (ptr2 == NULL) {
  printf("Failed. Unable to resize memory");
} else {
  ptr1 = ptr2; // safe to commit only after success
}
```

## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.87
- **중복 검사 결과:** 신규 생성 (New discovery)

## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[C Tutorial]]
- **관련 개념:** [[C Memory Deallocate]], [[C Memory Struct]], [[C Memory RealLife]]
- **참조 맥락:** 메모리 재할당 — 구조체와 동적 메모리(Memory Struct) 챕터로 이어짐.

## 📚 출처 (Sources)
- [S1] W3Schools — C Reallocate Memory — https://www.w3schools.com/c/c_memory_reallocate.php

## 📝 변경 이력 (Change history)
- 2026-07-04: Initial draft synthesized from the W3Schools "C Reallocate Memory" page (Astra wiki-curation, P-Reinforce v3.1 format).
