Dynamic Memory Management

dynamic memory allocation

Imagine you are writing a program but you do not yet know how big things will get. Maybe the user will type one line of text, or maybe ten thousand lines. Maybe they will load a tiny photo or an enormous one. When you write the program, you cannot know — that only becomes clear while the program is running. Dynamic memory allocation is the way a C program asks the system for a chunk of memory at run time, sized to whatever it actually needs right now, instead of having to guess the size in advance.

Here is how it works in practice. A C program already has two kinds of memory it gets for free: global variables (fixed in size, decided when the program is built) and local variables that live on the stack (created and destroyed automatically as functions call each other). Dynamic allocation is a third source. You call a function like malloc(n) and say I need n bytes. The system finds an unused region of that size in a memory area called the heap, and hands you back a pointer — the address of the first byte. That memory is now yours to read and write, and it stays yours until you explicitly give it back with free(). The size n can be any number computed at run time; for example, malloc(count * sizeof(int)) reserves room for exactly as many integers as you discovered you need.

Why it matters: this is the foundation of nearly every interesting data structure — a list that grows, a tree, a buffer that holds a file of unknown length. It also comes with responsibility. In C there is no automatic cleanup: the memory you get from malloc() is not erased for you, the system will not free it on its own, and if you lose the pointer without freeing it, that memory is wasted until the program exits. Everything else in this field — leaks, dangling pointers, ownership — is really about managing this one power carefully.

int n = how_many_users(); /* known only at run time */ int *ids = malloc(n * sizeof(int)); if (ids == NULL) { /* out of memory */ } /* ... use ids[0] .. ids[n-1] ... */ free(ids);

Reserve room for exactly n integers, decided while the program runs, then return it when done.

Dynamic does not mean slow or magical — it means the size and timing are decided at run time, not at compile time. Forgetting to free what you allocate is the source of most memory bugs in C.

Also called
heap allocation堆積配置執行期配置