100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C

Memory Management in C

Understand C's memory layout — text, data, heap, and stack segments — and when to choose stack vs heap allocation.

Advanced CIntermediate13 min readJul 7, 2026
Analogies

1. Introduction

C gives programmers direct, low-level control over memory, which is both its greatest strength and its most common source of bugs. Unlike languages with automatic garbage collection, a C program is responsible for understanding where its data lives and, for some of it, when that data is freed. Every running C program's address space is conceptually divided into distinct memory segments — text, data (including BSS), heap, and stack — each with different lifetimes, growth behavior, and performance characteristics. Understanding this layout is foundational for writing efficient, correct programs and for reasoning about bugs like stack overflows, memory leaks, and dangling pointers.

🏏

Cricket analogy: C's manual memory control is like a captain personally managing which players bat, field, or rest rather than relying on an auto-selector, with segments like the playing XI (stack), reserves (heap), and permanent staff (data) each behaving differently.

2. Syntax

There is no single "syntax" for memory segments since they are a runtime/OS concept, but each segment corresponds to recognizable code patterns:

🏏

Cricket analogy: There's no rulebook page labeled 'memory segments,' but just as a scorer recognizes an over is a maiden from the pattern of dots rather than a label, a programmer recognizes each segment from the code pattern that produces it.

c
int global_initialized = 42;      /* data segment */
static int global_uninitialized;   /* bss segment  */

void demo(void) {
    int local_var = 10;            /* stack segment */
    int *heap_ptr = malloc(sizeof(int) * 100); /* heap segment */
    free(heap_ptr);
}

3. Explanation

A typical process image (the exact layout is platform- and OS-dependent, but the conceptual model is consistent) contains: the **text/code segment**, which holds the compiled machine instructions and is typically read-only and shared between processes running the same executable; the **data segment**, which holds global and static variables that are explicitly initialized with a non-zero value; the **BSS segment**, which holds global and static variables that are uninitialized or initialized to zero (the OS zero-fills this region at load time, so it doesn't need to be stored in the executable file); the **heap**, a region used for dynamic memory allocated at runtime via malloc/calloc/realloc, which conceptually grows upward toward higher addresses as more memory is requested; and the **stack**, used for function call frames — local variables, parameters, and return addresses — which conceptually grows downward from high addresses and shrinks automatically as functions return.

🏏

Cricket analogy: The text segment is like the fixed laws of cricket printed in the rulebook, the data segment is like a team's pre-set batting order printed on the card, BSS is like blank scorecards ready to be filled to zero, the heap is like extra players called up as the tournament grows, and the stack is like the current over's ball-by-ball sequence that clears itself once the over ends.

Stack allocation is extremely fast: it's just a matter of moving a stack pointer, and memory is reclaimed automatically the moment a function returns, with no possibility of a leak. Its downsides are a fixed, relatively small size (often a few MB, configurable but limited) and automatic deallocation, meaning you cannot return a pointer to a local stack variable and expect it to remain valid. Heap allocation, by contrast, is explicit and manual: you call malloc, calloc, or realloc to reserve memory that persists until you call free on it (or the program ends). This makes the heap suitable for data whose size isn't known at compile time, or whose lifetime must outlive the function that created it, at the cost of being slower (due to allocator bookkeeping) and requiring careful management to avoid memory leaks (forgetting to free), dangling pointers (using memory after it's freed), and fragmentation (heap space split into many small, non-contiguous free blocks over time, making large allocations harder to satisfy even when total free memory is sufficient).

🏏

Cricket analogy: The stack is like a quick single run between wickets, fast and automatically over once completed, but limited by the pitch's length, while the heap is like arranging a benefit match manually — flexible but requiring you to personally book the ground (free it) or risk it sitting unused (a leak).

For completeness, the three core dynamic-memory functions are: malloc(size), which reserves size bytes of uninitialized memory and returns a pointer (or NULL on failure); calloc(n, size), which reserves space for n elements of size bytes each and zero-initializes the entire block; realloc(ptr, new_size), which resizes a previously allocated block, possibly moving it, and preserves existing contents up to the smaller of the old and new sizes; and free(ptr), which releases memory back to the heap allocator so it can be reused. Every successful malloc/calloc/realloc call should eventually be matched with exactly one free call.

🏏

Cricket analogy: malloc(size) is like requesting a fresh, unmarked scorecard of a given size; calloc(n, size) is like requesting n pre-zeroed scorecards for a whole tournament; realloc resizes an existing scorecard mid-series while keeping past entries; and free() is like returning the scorecard to the pavilion once the match series ends.

Two opposite failure modes to watch for: a **stack overflow**, caused by excessive recursion depth or very large local arrays (e.g., int buffer[10000000]; inside a function) that exceeds the stack's fixed size and crashes the program; and **heap fragmentation/leaks**, caused by repeated allocate/free cycles of varying sizes or by simply forgetting to free memory, which can degrade performance or exhaust available memory over a long-running program's lifetime.

Tip: as a rule of thumb, prefer stack allocation for small, fixed-size, short-lived data (fast and leak-proof), and reach for heap allocation only when the size is unknown until runtime, the data is large, or it must outlive the function that created it.

4. Example

c
#include <stdio.h>
#include <stdlib.h>

int global_data = 100;       /* data segment: initialized global */
static int global_bss;        /* bss segment: uninitialized global */

void stack_demo(void) {
    int local_array[5] = {1, 2, 3, 4, 5};  /* stack: freed automatically */
    printf("Stack address of local_array: %p\n", (void *)local_array);
}

void heap_demo(int n) {
    int *heap_array = malloc(n * sizeof(int)); /* heap: manual lifetime */
    if (heap_array == NULL) {
        fprintf(stderr, "Allocation failed\n");
        return;
    }
    for (int i = 0; i < n; i++) {
        heap_array[i] = i * i;
    }
    printf("Heap address of heap_array: %p\n", (void *)heap_array);
    printf("heap_array[3] = %d\n", heap_array[3]);
    free(heap_array);   /* must free manually */
    heap_array = NULL;  /* avoid dangling pointer */
}

int main(void) {
    stack_demo();
    heap_demo(5);
    printf("global_data (data seg) = %d\n", global_data);
    printf("global_bss (bss seg)  = %d\n", global_bss);
    return 0;
}

5. Output

text
Stack address of local_array: 0x7ffee2a1c9d0
Heap address of heap_array: 0x55d8f3a1a2a0
heap_array[3] = 9
global_data (data seg) = 100
global_bss (bss seg)  = 0

(Actual addresses vary by run, OS, and ASLR settings;
note heap and stack addresses are far apart in the address space.)

6. Key Takeaways

  • A C process's address space is conceptually divided into text/code, data, BSS, heap, and stack segments.
  • Text holds instructions; data holds initialized globals/statics; BSS holds zero/uninitialized globals/statics.
  • The stack holds function call frames and local variables; it grows/shrinks automatically and is very fast.
  • The heap holds dynamically allocated memory (malloc/calloc/realloc) with manual, programmer-controlled lifetime via free.
  • Stack memory is limited and auto-freed on function return; heap memory is larger but must be explicitly freed.
  • Stack overflow (excess recursion/large locals) and heap leaks/fragmentation are the classic failure modes of each region.

Practice what you learned

Was this page helpful?

Topics covered

#CProgrammingStudyNotes#Programming#MemoryManagementInC#Memory#Management#Syntax#Explanation#StudyNotes#SkillVeris#ExamPrep

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse