Files
2nd/10_Wiki/Dev/Topic_C/C_Memory_Deallocate.md
T
Antigravity Agent 1cfd3bbb56 docs(10_Wiki): 위키 구조 정리 — 언어 튜토리얼 카테고리 폴더 제거 + 신규 자산 동기화
Topic_CSS/Topic_HTML/Topic_JavaScript/Topic_Prompt/Topic_Comfyui 등 기존 카테고리 폴더를 정리하고,
Topic_Graphic/Dev 등 신규 산출물과 Topics 내부 세션/메모리 기록을 동기화.
2026-07-05 00:10:59 +09:00

4.8 KiB

id, title, category, status, verification_status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, created_at, updated_at, review_reason, merge_history, tags, raw_sources, applied_in, github_commit
id title category status verification_status canonical_id aliases duplicate_of source_trust_level confidence_score created_at updated_at review_reason merge_history tags raw_sources applied_in github_commit
c-memory-deallocate C Deallocate Memory Programming_Language draft conceptual
free() function
memory leak
set pointer to NULL
C 메모리 해제
B 0.87 2026-07-04 2026-07-04
c
programming-language
w3schools
memory-management
free
memory-leak
https://www.w3schools.com/c/c_memory_deallocate.php

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):

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)

📚 출처 (Sources)

📝 변경 이력 (Change history)

  • 2026-07-04: Initial draft synthesized from the W3Schools "C Deallocate Memory" page (Astra wiki-curation, P-Reinforce v3.1 format).