//calloc
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n = 5;
printf("Enter number of values:\n");
scanf("%d",&n);
ptr = (int *)calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
printf("\n");
for (int i = 0; i < n; i++) {
ptr[i] = i *10+10;
}
printf("After assigning values:\n");
for (int i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}
printf("\n");
free(ptr);
ptr = NULL;
return 0;
}
i
Output
After assigning values:
10 20 30 40 50
After assigning values:
10 20 30 40 50🟦 Step 9: Free the Allocated Memory
free(ptr);
free(ptr);Explanation
The free() function releases the dynamically allocated memory.
Before free():
ptr
↓
+-----+-----+-----+-----+-----+
| 10 | 20 | 30 | 40 | 50 |
+-----+-----+-----+-----+-----+
After free():
Memory Released to the Operating System
The memory is no longer available for use.
🟦 Step 10: Assign NULL to the Pointer
ptr = NULL;
ptr = NULL;Why?
After calling free(), the pointer still contains the old memory address.
Such a pointer is called a dangling pointer.
Assigning NULL makes the pointer safe.
Before
ptr
↓
0x7ffab120
ptr
↓
0x7ffab120After
ptr
↓
NULL
ptr
↓
NULL📊 Program Flow Diagram
Start
│
▼
Read n
│
▼
Allocate Memory using calloc()
│
▼
Is ptr == NULL?
│
┌─┴───────────────┐
│ │
Yes No
│ │
▼ ▼
Print Error Store Values
Exit │
▼
Print Values
│
▼
Free Memory
│
▼
ptr = NULL
│
▼
End
Start
│
▼
Read n
│
▼
Allocate Memory using calloc()
│
▼
Is ptr == NULL?
│
┌─┴───────────────┐
│ │
Yes No
│ │
▼ ▼
Print Error Store Values
Exit │
▼
Print Values
│
▼
Free Memory
│
▼
ptr = NULL
│
▼
End🖥 Sample Execution
Input
Enter number of values:
5
Enter number of values:
5Output
After assigning values:
10 20 30 40 50
After assigning values:
10 20 30 40 50📦 Memory Representation
Before Allocation
ptr
↓
NULL
ptr
↓
NULLAfter calloc()
ptr
↓
+----+----+----+----+----+
| 0 | 0 | 0 | 0 | 0 |
+----+----+----+----+----+
ptr
↓
+----+----+----+----+----+
| 0 | 0 | 0 | 0 | 0 |
+----+----+----+----+----+After Storing Values
ptr
↓
+----+----+----+----+----+
|10 |20 |30 |40 |50 |
+----+----+----+----+----+
ptr
↓
+----+----+----+----+----+
|10 |20 |30 |40 |50 |
+----+----+----+----+----+After free()
Memory Released
ptr
↓
NULL
Memory Released
ptr
↓
NULL🌟 Advantages of calloc()
-
✅ Allocates memory dynamically during program execution.
-
✅ Initializes all allocated memory to 0.
-
✅ Helps avoid using uninitialized data.
-
✅ Suitable when the number of elements is known only at runtime.
⚠ Precautions
-
Always check whether
calloc() returns NULL.
-
Always access elements within the allocated range (
0 to n-1).
-
Always call
free() when the memory is no longer needed.
-
Set the pointer to
NULL after free() to avoid dangling pointers.
calloc() returns NULL.
0 to n-1).
free() when the memory is no longer needed.
NULL after free() to avoid dangling pointers.
No comments:
Post a Comment