Files
2nd/10_Wiki/Dev/Topic_C/C_Memory_Allocate.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.9 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-allocate C Allocate Memory Programming_Language draft conceptual
malloc calloc
static vs dynamic memory
stack memory
C 메모리 할당
B 0.87 2026-07-04 2026-07-04
c
programming-language
w3schools
memory-management
malloc
calloc
https://www.w3schools.com/c/c_memory_allocate.php

C Allocate Memory

🎯 한 줄 통찰 (One-line insight)

sizeof(*ptr1) and sizeof(ptr1) look nearly identical but measure two completely different things — the FIRST measures the size of the data the pointer points to (correct for allocation), while the SECOND measures the size of the pointer variable itself (usually 8 bytes, the address size) — and the source explicitly flags forgetting the * as a real, easy-to-make mistake that silently allocates the wrong amount of memory. [S1]

🧠 핵심 개념 (Core concepts)

  • Static memory — reserved automatically at COMPILE time for regular variables; fixed size, cannot be resized after creation (e.g. an array declared for 20 elements always occupies that space, even if only 12 are used). [S1]
  • Dynamic memory — reserved at RUNTIME, giving full programmer control over how much memory is used; only accessible via pointers, never owned by a plain variable. [S1]
  • malloc(size) — allocates size bytes; the content is UNPREDICTABLE/uninitialized until written. [S1]
  • calloc(amount, size) — allocates amount items of size bytes each, AND zero-initializes all of it; slightly less efficient than malloc() because of the zeroing step. [S1]
  • sizeof(*ptr) vs sizeof(ptr) — the former measures the pointed-to data's size (correct for sizing an allocation); the latter measures the pointer variable's own size (usually 8 bytes on 64-bit systems), a common mistake. [S1]
  • sizeof can't measure total allocated memory — it only reports the size of ONE element's type, so total dynamic allocation size must be computed manually (count * sizeof(type)). [S1]
  • Stack memory — a form of dynamic memory automatically reserved for variables declared INSIDE functions; freed automatically when the function returns; excessive recursion can exhaust it, causing a "stack overflow." [S1]

📖 세부 내용 (Details)

  • Static memory waste example: int students[20]; // reserves 80 bytes even if only 12 students actually attend. [S1]
  • Correctly sizing a dynamic allocation with sizeof(*ptr): int *ptr1, *ptr2; ptr1 = malloc(sizeof(*ptr1)); ptr2 = calloc(1, sizeof(*ptr2));. [S1]
  • Computing total dynamic memory manually (sizeof alone can't do it): int *students; int numStudents = 12; students = calloc(numStudents, sizeof(*students)); printf("%d", numStudents * sizeof(*students)); // 48 bytes. [S1]

⚖️ 모순 및 업데이트 (Contradictions & updates)

  • *sizeof(ptr) vs sizeof(ptr)의 차이: 별표를 빠뜨리면 포인터가 가리키는 데이터의 크기가 아니라 포인터 자체의 크기(보통 8바이트)를 측정하게 된다는 점이 실수하기 쉬운 부분으로 명시적으로 경고됨. [S1]
  • 정적 메모리의 낭비 가능성: 20명분 배열을 만들었는데 실제 12명만 참여하면 8명분 공간이 낭비되지만, 프로그램은 정상 작동하며 손상되지 않는다는 점이 확인됨(단지 비효율적일 뿐). [S1]

🛠️ 적용 사례 (Applied in summary)

학생 수(numStudents)만큼만 calloc으로 메모리를 할당해 정적 배열의 낭비 문제를 해결하는 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]

💻 코드 패턴 (Code patterns)

Correctly sizing an allocation using sizeof(*ptr), not sizeof(ptr) (C):

int *ptr1, *ptr2;
ptr1 = malloc(sizeof(*ptr1));       // correct: size of the pointed-to int
ptr2 = calloc(1, sizeof(*ptr2));    // correct: size of the pointed-to int
// sizeof(ptr1) would instead measure the pointer itself (usually 8 bytes)

검증 상태 및 신뢰도

  • 상태: 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 Allocate Memory" page (Astra wiki-curation, P-Reinforce v3.1 format).