C Memory Management
1. Memory in C
C programs use two main types of memory:
| Memory Type | Description |
|---|---|
| Stack | Stores local variables, function calls, and automatic data. Managed automatically. |
| Heap | Stores dynamically allocated memory. Managed manually using malloc/free. |
2. Static vs Dynamic Memory Allocation
| Type | Description | Example |
|---|---|---|
| Static | Memory size known at compile time. Allocated automatically on stack. | int a[10]; |
| Dynamic | Memory size determined at runtime. Allocated manually on heap. | malloc(), calloc() |
3. Dynamic Memory Allocation Functions
C provides the following functions in <stdlib.h>:
| Function | Description |
|---|---|
malloc(size_t size) |
Allocates memory of given size in bytes. Returns void*. |
calloc(size_t n, size_t size) |
Allocates memory for n elements, initializes to 0. |
realloc(void *ptr, size_t size) |
Resizes previously allocated memory. |
free(void *ptr) |
Frees memory allocated on heap. |
4. Example: Using malloc
Output:
5. Example: Using calloc
Output:
6. Example: Using realloc
Output:
7. Memory Leaks
-
Memory leak occurs when allocated memory is not freed.
-
Always use
free()after dynamic allocation. -
Example:
8. Key Points About C Memory Management
-
Stack memory: automatic, fast, limited size.
-
Heap memory: manual, dynamic, larger but slower.
-
Use
malloc,calloc,reallocfor dynamic allocation. -
Use
free()to release heap memory. -
Avoid memory leaks by freeing allocated memory.
-
Proper memory management is crucial in embedded systems, large applications, and performance-critical programs.
