Understanding calloc() in C Standard Library
calloc() stands for:
Contiguous Allocation
It is used in C to dynamically allocate memory for
multiple elements and initialize all bytes to zero.
Syntax
void *calloc(size_t num, size_t size);
Where:
num → number of elements
size → size of each element in bytes
Returns:
Pointer to allocated memory
NULL if allocation fails
Main Difference from malloc()
|
Function |
Initialization |
|
malloc() |
Garbage values |
|
calloc() |
All bytes initialized to 0 |
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int i;
arr = (int *)calloc(5, sizeof(int));
if (arr == NULL) {
printf("Memory allocation
failed\n");
return 1;
}
for(i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
free(arr);
return 0;
}
Output
0 0 0 0 0
Because calloc() initializes memory to zero.
Step-by-Step Explanation
1. Allocation
calloc(5, sizeof(int));
Requests memory for:
5 integers
each of size sizeof(int)
If int = 4 bytes:
5 × 4 = 20 bytes
2. Contiguous Memory
Memory layout:
+----+----+----+----+----+
| 0 | 0
| 0 | 0 | 0 |
+----+----+----+----+----+
All initialized to zero.
Internal Working
Simplified process:
calloc() request
↓
Heap manager allocates block
↓
Memory initialized to zero
↓
Pointer returned
Equivalent Using malloc()
calloc() is roughly similar to:
ptr = malloc(num * size);
memset(ptr, 0, num * size);
But calloc() is often optimized internally.
malloc() vs calloc()
|
Feature |
malloc() |
calloc() |
|
Arguments |
1 |
2 |
|
Initialization |
No |
Yes (zero) |
|
Speed |
Slightly faster |
Slightly slower |
|
Usage |
General allocation |
Arrays/initialized memory |
Example: Dynamic Array
int *marks;
marks = (int *)calloc(100, sizeof(int));
Allocates memory for:
100 integers
initialized to 0
Important Notes
Zero Initialization
For integers:
0
For pointers:
NULL (all bits zero on most systems)
For floating point:
0.0
Common Errors
1. Forgetting free()
free(arr);
Without freeing:
Memory leak occurs
2. Accessing Beyond Allocated Memory
arr[10] = 5;
when only 5 elements allocated → undefined behavior.
3. NULL Pointer Access
Always check:
if(arr == NULL)
Using with Structures
Example:
struct Student *s;
s = (struct Student *)calloc(1, sizeof(struct Student));
Useful because all fields start initialized to zero.
Best Practices
✅ Check for NULL
✅
Free memory after use
✅
Use calloc() when zero initialization needed
✅
Avoid out-of-bounds access
Real-Life Analogy
Imagine booking apartment rooms:
malloc():
Gives rooms with old items left inside.
calloc():
Gives freshly cleaned empty rooms.
Summary
calloc():
Dynamically allocates contiguous memory
Initializes memory to zero
Useful for arrays and structures
Safer than malloc() when initialization is needed
Formula:
free() in C, /proc/meminfo and
Memory
free() in C
free() is used to release dynamically allocated memory back
to the system.
It works with memory allocated using:
malloc()
calloc()
realloc()
Syntax
void free(void *ptr);
ptr → pointer to memory block previously allocated
dynamically
Why free() is Important
Heap memory is not automatically released like stack memory.
If memory is not freed:
Memory leaks occur
Program memory usage keeps increasing
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
ptr = (int *)malloc(sizeof(int));
if(ptr == NULL) {
return 1;
}
*ptr = 100;
printf("%d\n", *ptr);
free(ptr);
return 0;
}
What Happens Internally
malloc() allocates heap memory
↓
Program uses memory
↓
free() marks block as available
↓
Allocator may reuse block later
Important:
Memory is returned to allocator/runtime
Not necessarily immediately returned to OS
Common Memory Errors
1. Memory Leak
int *p = malloc(100);
/* forgot free() */
Allocated memory becomes unreachable.
2. Dangling Pointer
free(p);
*p = 10;
Using freed memory → undefined behavior.
3. Double Free
free(p);
free(p);
Can crash program or corrupt heap.
Good Practice
free(p);
p = NULL;
Prevents accidental reuse.
/proc/meminfo in Linux
/proc/meminfo is a virtual file containing detailed memory
statistics.
View it using:
cat /proc/meminfo
Example Output
MemTotal:
16384256 kB
MemFree: 2048000 kB
MemAvailable: 6200000 kB
Buffers: 300000 kB
Cached: 2500000 kB
SwapTotal: 2097148 kB
SwapFree: 1800000 kB
Important Fields
|
Field |
Meaning |
|
MemTotal |
Total RAM |
|
MemFree |
Completely unused RAM |
|
MemAvailable |
Memory available for
applications |
|
Buffers |
Kernel buffers |
|
Cached |
File cache memory |
|
SwapTotal |
Total swap space |
|
SwapFree |
Free swap space |
Why Cached Memory Matters
Linux uses free RAM for caching files to improve performance.
So:
Low MemFree does NOT necessarily mean low memory.
MemAvailable is more useful.
Example Interpretation
MemTotal: 8 GB
MemAvailable: 5 GB
Meaning:
System can still provide ~5 GB without heavy swapping.
Relationship Between free() and System Memory
When a program calls free():
Program frees heap block
↓
Allocator marks block reusable
↓
Kernel memory statistics may change
However:
Freed memory may remain inside process heap
It may not immediately reduce MemFree
Modern allocators:
Reuse freed blocks efficiently
Viewing Memory Usage
free Command
free -h
Displays:
RAM
Used memory
Free memory
Swap
top
top
Shows:
Per-process memory usage
vmstat
vmstat
Displays:
Virtual memory statistics
Paging activity
Linux Memory Management Concepts
Heap Memory
Dynamic allocation (malloc/calloc) uses:
Process heap
Heap grows as needed.
Virtual Memory
Each process gets:
Virtual address space
Kernel maps:
Virtual pages → Physical frames
Page Faults
Accessing nonresident page:
Triggers page fault
Kernel loads page into RAM
Simplified Memory Flow
malloc()
↓
Heap allocation
↓
Program uses memory
↓
free()
↓
Memory reusable
Out of Memory (OOM)
If system memory exhausted:
Linux may invoke:
OOM Killer
to terminate processes.
Key Takeaways
free()
Releases dynamically allocated heap memory
Prevents memory leaks
Essential for long-running programs
/proc/meminfo
Provides detailed Linux memory statistics
Useful for monitoring RAM and swap usage
Linux Memory
Uses virtual memory
Employs paging and caching
Optimizes memory reuse dynamically
No comments:
Post a Comment