--- id: c-memory-reallife title: "C Memory Management Example" category: "Programming_Language" status: "draft" verification_status: "conceptual" canonical_id: "" aliases: ["dynamic array list", "growable list implementation", "C 메모리 관리 실전 예제"] duplicate_of: "" source_trust_level: "B" confidence_score: 0.86 created_at: 2026-07-04 updated_at: 2026-07-04 review_reason: "" merge_history: [] tags: ["c", "programming-language", "w3schools", "memory-management", "dynamic-array"] raw_sources: ["https://www.w3schools.com/c/c_memory_reallife.php"] applied_in: [] github_commit: "" --- # [[C Memory Management Example]] ## 🎯 한 줄 통찰 (One-line insight) The chapter directly answers WHY growable lists grow by a chunk of 10 rather than 1-at-a-time: reallocating memory too FREQUENTLY is inefficient even though it wastes less space, so the design deliberately trades a small amount of unused memory for far fewer (and cheaper) reallocation calls — an explicit memory-vs-performance balancing act rather than an arbitrary constant. [S1] ## 🧠 핵심 개념 (Core concepts) - **Growable list via struct + dynamic memory** — a `struct list { int *data; int numItems; int size; }` tracks the actual data pointer, how many items are currently used, and how much capacity is currently allocated. [S1] - **Batch-growth strategy** — when the list fills up, capacity grows by a FIXED CHUNK (+10 items) rather than exactly by 1, trading some unused memory for fewer, cheaper reallocation calls. [S1] - **Safe realloc pattern reused** — `addToList()` uses a temporary pointer (`tmp`) for the `realloc()` result, only committing `myList->data`/`myList->size` AFTER confirming `tmp` isn't NULL. [S1] - **Struct passed by pointer to a function** — `addToList(struct list *myList, int item)` receives the list by pointer (using `->`) so it can permanently mutate the caller's actual list state, not a copy. [S1] - **Fixed-size arrays can't do this** — the chapter opens by contrasting this against regular C arrays, whose length is fixed at creation and can never grow. [S1] ## 📖 세부 내용 (Details) - The list struct and its three roles: `struct list { int *data; int numItems; int size; };` — `data` points to the dynamic storage, `numItems` tracks current fill level, `size` tracks total current capacity. [S1] - The growth-trigger check inside `addToList()`: `if (myList->numItems == myList->size) { int newSize = myList->size + 10; int *tmp = realloc(myList->data, newSize * sizeof(int)); if (tmp == NULL) { printf("Memory resize failed\n"); return; } myList->data = tmp; myList->size = newSize; }`. [S1] - Appending after ensuring capacity: `myList->data[myList->numItems] = item; myList->numItems++;`. [S1] - Explicit rationale for the +10 chunk size: "Optimizing is a balancing act between memory and performance... reallocating memory too frequently can be inefficient." [S1] ## ⚖️ 모순 및 업데이트 (Contradictions & updates) - **+10씩 늘리는 이유는 메모리와 성능의 균형**: 정확히 필요한 만큼만 늘리지 않고 10개씩 뭉텅이로 늘리는 이유가 재할당을 너무 자주 하면 비효율적이기 때문이라는 점이 명시적으로 설명됨 — 정확한 개수(예: 44개)를 미리 안다면 한 번에 그만큼만 할당하는 것이 더 낫다고도 언급됨. [S1] ## 🛠️ 적용 사례 (Applied in summary) 44개의 항목을 하나씩 추가하면서 필요할 때마다 자동으로 용량을 10개씩 늘려가는 리스트 구현이 원문에서 직접 실전 활용 사례로 제시되며, 배열/구조체/포인터/동적 메모리 챕터 전체를 종합한 완결편 역할을 한다. [S1] ## 💻 코드 패턴 (Code patterns) Growing a dynamic list by a fixed chunk size using the safe temporary-pointer realloc pattern (C): ```c void addToList(struct list *myList, int item) { if (myList->numItems == myList->size) { int newSize = myList->size + 10; int *tmp = realloc(myList->data, newSize * sizeof(int)); if (tmp == NULL) { printf("Memory resize failed\n"); return; } myList->data = tmp; myList->size = newSize; } myList->data[myList->numItems] = item; myList->numItems++; } ``` ## ✅ 검증 상태 및 신뢰도 - **상태:** draft - **검증 단계:** conceptual - **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body) - **신뢰 점수:** 0.86 - **중복 검사 결과:** 신규 생성 (New discovery) ## 🔗 지식 그래프 (Knowledge Graph) - **상위/루트:** [[C Tutorial]] - **관련 개념:** [[C Memory Struct]], [[C Functions]], [[C Structs Pointers]] - **참조 맥락:** 포인터 및 메모리 섹션 마지막 — 함수(Functions) 섹션으로 이어짐. ## 📚 출처 (Sources) - [S1] W3Schools — C Memory Management Example — https://www.w3schools.com/c/c_memory_reallife.php ## 📝 변경 이력 (Change history) - 2026-07-04: Initial draft synthesized from the W3Schools "C Memory Management Example" page (Astra wiki-curation, P-Reinforce v3.1 format).