Page Replacement
Linux uses page replacement algorithms to choose
victim pages.
Concepts used:
LRU-like mechanisms
Active/inactive page lists
Working set ideas
Goal:
Keep frequently used pages in RAM.
Linux Memory Zones
Physical memory divided into zones:
|
Zone |
Purpose |
|
DMA |
Direct Memory Access |
|
Normal |
Regular kernel memory |
|
HighMem |
High memory (32-bit systems) |
Buddy System Allocator
Linux uses the Buddy Allocator for physical memory
allocation.
Idea:
Memory split into power-of-two blocks.
Adjacent free buddies merged.
Advantages:
Fast allocation/deallocation
Reduced fragmentation
Slab Allocator
Used for kernel objects.
Caches frequently used objects:
Process descriptors
Inodes
File structures
Advantages:
Faster allocation
Less overhead
Memory Protection
Linux provides:
User mode vs kernel mode protection
Page permissions:
Read
Write
Execute
Prevents:
Illegal access
Process interference
Important Linux Memory Concepts
Page Cache
Caches file data in RAM to reduce disk access.
Dirty Pages
Modified pages not yet written to disk.
mmap()
Maps files/devices directly into memory.
NUMA
Non-Uniform Memory Access systems optimize locality in
multi-CPU machines.
Useful Linux Memory Commands
|
Command |
Purpose |
|
free -h |
View memory usage |
|
top / htop |
Monitor processes |
|
vmstat |
Virtual memory statistics |
|
cat /proc/meminfo |
Detailed memory info |
|
pmap |
Process memory map |
Memory Allocation Flow
Process requests memory
↓
Virtual address assigned
↓
Page mapped to physical frame
↓
If page absent → page fault
↓
Kernel loads page into RAM
Memory Problems
|
Problem |
Description |
|
Fragmentation |
Wasted memory space |
|
Thrashing |
Excessive paging/swapping |
|
Memory Leak |
Memory not released |
|
OOM |
Out Of Memory condition |
Linux handles severe shortages using:
OOM Killer
Summary
Linux memory management combines:
Virtual memory
Paging
Swapping
Page replacement
Buddy allocator
Slab allocator
Memory protection
to efficiently manage RAM and support multitasking
with high performance.
Understanding malloc()
Understanding malloc() in C Standard Library
malloc() stands for:
Memory Allocation
It is a function in the C standard library used to
dynamically allocate memory during program execution.
Syntax
void *malloc(size_t size);
size → number of bytes to allocate
Returns:
Pointer to allocated memory
NULL if allocation fails
Why Use malloc()?
Normally, variables are stored in:
Stack memory (automatic allocation)
But stack memory:
Has limited size
Exists only within scope
malloc() allocates memory in the heap, which:
Is larger
Persists until manually freed
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
ptr = (int *)malloc(sizeof(int));
if (ptr == NULL) {
printf("Memory allocation
failed\n");
return 1;
}
*ptr = 25;
printf("Value = %d\n",
*ptr);
free(ptr);
return 0;
}
Step-by-Step Explanation
1. Pointer Declaration
int *ptr;
Pointer to integer.
2. Allocate Memory
ptr = (int *)malloc(sizeof(int));
What happens internally:
sizeof(int) gives memory size (usually 4 bytes)
malloc() requests memory from heap
Returns starting address
Example:
Heap Memory:
+----+----+----+----+
| 25 | | |
|
+----+----+----+----+
^
ptr
3. NULL Check
if (ptr == NULL)
Important because allocation may fail when:
Heap memory exhausted
System limits reached
4. Store Value
*ptr = 25;
Dereferencing pointer to access allocated memory.
5. Free Memory
free(ptr);
Releases heap memory back to OS/runtime allocator.
Without free():
Memory leak occurs
Stack vs Heap
|
Feature |
Stack |
Heap |
|
Allocation |
Automatic |
Manual (malloc) |
|
Speed |
Faster |
Slower |
|
Size |
Limited |
Larger |
|
Lifetime |
Function scope |
Until free() |
|
Managed by |
Compiler |
Programmer |
Dynamic Array Example
int *arr;
arr = (int *)malloc(5 * sizeof(int));
Allocates memory for 5 integers.
Memory layout:
+----+----+----+----+----+
| |
| | |
|
+----+----+----+----+----+
Access normally:
arr[0] = 10;
arr[1] = 20;
Common Mistakes
1. Forgetting free()
malloc(...);
Without free() → memory leak.
2. Using Uninitialized Memory
int *p = malloc(sizeof(int));
printf("%d", *p);
Value is garbage.
Use:
calloc()
or initialize manually
calloc() vs malloc()
|
Function |
Initialization |
|
malloc() |
Garbage values |
|
calloc() |
Zero initialized |
Example:
calloc(5, sizeof(int));
realloc()
Changes size of previously allocated memory.
ptr = realloc(ptr, new_size);
Useful for:
Dynamic arrays
Resizable buffers
Internal Working of malloc()
Simplified process:
Program requests memory
↓
malloc() asks heap manager
↓
Heap manager finds free block
↓
Address returned to program
Internally Linux may use:
brk()
mmap()
to obtain memory from kernel.
Memory Errors Related to malloc()
|
Error |
Description |
|
Memory Leak |
Memory not freed |
|
Dangling Pointer |
Using freed memory |
|
Double Free |
Freeing same block twice |
|
Buffer Overflow |
Writing beyond allocated size |
Best Practices
✅ Always check for NULL
✅
Free allocated memory
✅
Avoid double free
✅
Initialize memory
✅
Set pointer to NULL after free
Example:
free(ptr);
ptr = NULL;
Simple Real-Life Analogy
Imagine heap memory as renting storage boxes.
malloc() → rents a box
Pointer → stores box address
free() → returns box
If you forget to return:
Storage space gets wasted.
Summary
malloc():
Dynamically allocates memory from heap
Returns pointer to allocated block
Requires manual memory management using free()
Essential for dynamic data structures:
Linked lists
Trees
Dynamic arrays
Graphs
Get smarter responses, upload files and images, and
more.
Log in
Sign up for free
Top of Form
Bottom of Form
We use cookies
No comments:
Post a Comment