--- id: c-memory-deallocate title: "C Deallocate Memory" category: "Programming_Language" status: "draft" verification_status: "conceptual" canonical_id: "" aliases: ["free() function", "memory leak", "set pointer to NULL", "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", "free", "memory-leak"] raw_sources: ["https://www.w3schools.com/c/c_memory_deallocate.php"] applied_in: [] github_commit: "" --- # [[C Deallocate Memory]] ## 🎯 한 줄 통찰 (One-line insight) A memory leak isn't caused by forgetting `free()` in the obvious sense — the source's three worked examples show it happens when the POINTER itself is lost (overwritten to point elsewhere, scoped inside a function that ends, or clobbered by a failed `realloc()` returning NULL) while the memory it referenced is STILL allocated but now permanently unreachable — meaning the memory isn't the problem, losing the only handle to it is. [S1] ## 🧠 핵심 개념 (Core concepts) - **`free(pointer)`** — releases previously allocated dynamic memory back for reuse by other parts of the program or other programs. [S1] - **Set to NULL after freeing** — best practice; prevents accidentally continuing to use a freed (now invalid) pointer. [S1] - **Memory leak** — dynamically allocated memory that is never freed, typically because the ONLY pointer referencing it was lost, not because `free()` was simply forgotten in an obvious spot. [S1] - **Leak pattern 1: pointer overwritten** — reassigning a pointer variable to a new address (e.g. `&x`) severs its only link to the previously `calloc()`'d memory. [S1] - **Leak pattern 2: pointer scoped to a function** — a local pointer variable disappears when its function returns, but the memory it pointed to remains allocated and now unreachable. [S1] - **Leak pattern 3: failed `realloc()` overwrites the original pointer** — if `realloc()` fails and returns `NULL`, assigning that `NULL` directly back to the SAME variable destroys the only reference to the still-valid original memory. [S1] ## 📖 세부 내용 (Details) - Basic free with error checking and NULL-setting: `int *ptr; ptr = malloc(sizeof(*ptr)); if (ptr == NULL) { printf("Unable to allocate memory"); return 1; } *ptr = 20; free(ptr); ptr = NULL;`. [S1] - Leak via pointer reassignment: `int x = 5; int *ptr; ptr = calloc(2, sizeof(*ptr)); ptr = &x;` — the calloc'd memory is now unreachable. [S1] - Leak via function-scoped pointer: `void myFunction() { int *ptr; ptr = malloc(sizeof(*ptr)); }` — memory allocated inside persists after the function returns but can never be freed or accessed again. [S1] - Leak via unchecked realloc failure: `ptr = realloc(ptr, 2*sizeof(*ptr));` — if this fails, `ptr` becomes NULL and the original memory address is lost forever (the correct fix, shown in the Reallocate chapter, is to use a TEMPORARY pointer for the realloc result). [S1] ## ⚖️ 모순 및 업데이트 (Contradictions & updates) - **메모리 누수의 진짜 원인은 포인터 분실**: free()를 안 써서가 아니라, 메모리를 가리키던 유일한 포인터가 덮어써지거나(재대입/함수 종료/realloc 실패) 사라져서 더 이상 접근할 수 없게 되는 것이 메모리 누수의 실제 메커니즘이라는 점이 세 가지 예제로 구체적으로 증명됨. [S1] ## 🛠️ 적용 사례 (Applied in summary) 현재 발견된 실제 적용 사례가 없습니다 — free() 후 포인터를 NULL로 설정하는 습관이 실수로 해제된 메모리를 재사용하는 버그를 방지하는 실전 관행으로 강조된다. [S1] ## 💻 코드 패턴 (Code patterns) Freeing memory and setting the pointer to NULL to prevent accidental reuse (C): ```c int *ptr; ptr = malloc(sizeof(*ptr)); if (ptr == NULL) { printf("Unable to allocate memory"); return 1; } *ptr = 20; free(ptr); ptr = NULL; // prevents accidental use-after-free ``` ## ✅ 검증 상태 및 신뢰도 - **상태:** draft - **검증 단계:** conceptual - **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body) - **신뢰 점수:** 0.87 - **중복 검사 결과:** 신규 생성 (New discovery) ## 🔗 지식 그래프 (Knowledge Graph) - **상위/루트:** [[C Tutorial]] - **관련 개념:** [[C Memory Allocate]], [[C Memory Reallocate]], [[C Null]] - **참조 맥락:** 메모리 해제 — 메모리 재할당(Memory Reallocate) 챕터로 이어짐. ## 📚 출처 (Sources) - [S1] W3Schools — C Deallocate Memory — https://www.w3schools.com/c/c_memory_deallocate.php ## 📝 변경 이력 (Change history) - 2026-07-04: Initial draft synthesized from the W3Schools "C Deallocate Memory" page (Astra wiki-curation, P-Reinforce v3.1 format).