-
Notifications
You must be signed in to change notification settings - Fork 0
/
memorymanagement.c
94 lines (89 loc) · 2.53 KB
/
memorymanagement.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// //// Dynamic memory allocation
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr;
int n, p, i;
printf("\n-------------------------------");
printf(" \nNAME : SRUTHI O T \n");
printf("\nREGISTER NO : 20352059\n");
printf("\nDate : 09.06.21 \n");
printf("\nPROGRAM :MEMORY MANAGEMENT \n\n");
printf("---------------------------------\n");
printf("\n --------------------\n");
printf("| malloc |\n");
printf(" --------------------\n");
printf("Enter number of elements:");
scanf("%d", &n);
ptr = (int *)malloc(n * sizeof(int));
if (ptr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
printf("Memory successfully allocated using malloc.\n");
for (i = 0; i < n; ++i)
{
printf("enter elements : ");
scanf("%d", &p);
ptr[i] = p;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i)
{
printf("%d ", ptr[i]);
}
}
printf("\n\n --------------------\n");
printf("| calloc |\n");
printf(" --------------------\n");
printf("Enter number of elements:");
scanf("%d", &n);
ptr = (int *)calloc(n, sizeof(int));
if (ptr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
printf("Memory successfully allocated using calloc.\n");
for (i = 0; i < n; ++i)
{
printf("enter elements : ");
scanf("%d", &p);
ptr[i] = p;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i)
{
printf("%d ", ptr[i]);
}
printf("\n\n --------------------\n");
printf("| Realloc |\n");
printf(" --------------------\n");
printf("Enter new number of elements:");
scanf("%d", &n);
ptr = realloc(ptr, n * sizeof(int));
printf("Memory successfully re-allocated using realloc.\n");
printf("The elements of the array are: ");
for (i = 0; i < n; ++i)
{
printf("%d ", ptr[i]);
}
printf("\n\n --------------------\n");
printf("| free |\n");
printf(" --------------------\n");
if (ptr == NULL)
printf("Memory not allocated in ptr\n");
else
{
free(ptr);
printf("released memory using free() function\n");
}
return 0;
}
}