-
Notifications
You must be signed in to change notification settings - Fork 7
/
newAndDelete.cpp
54 lines (45 loc) · 1.14 KB
/
newAndDelete.cpp
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
#include<bits/stdc++.h>
using namespace std;
int main() {
/*
SMA: Static Memory Allocation
DMA: Dynamic Memory Allocation (Implemented using new and delete in C++)
In SMA, the amount of memory allocated to the declaration statements(int x, float y, etc) is decided
during Compile time only and cannot be changed. However, the memoery gets allocated when the program
comes in RAM
*/
int *x = NULL;
// Requesting memory for a new variable. nothrow signifies that if memory does
// not get assigned it does not throw an error
x = new(nothrow) int;
if (!x) {
cout << "Could not allocate memory\n";
}
else {
*x = 22;
cout << "Value of x is: " << *x << endl;
}
float *y = new(nothrow) float(11.111);
if (!y) {
cout << "Could not allocate memory\n";
}
else {
cout << "Value of y is: " << *y << endl;
}
// DMA for Arrays
int n = 10;
int *a = new int[10];
for (int i = 0; i < n; i++) {
a[i] = i + 1;
}
cout << "Array elements are: ";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
// Deallocating memory for variables
delete x;
delete y;
// Deallocating memory for array
delete []a;
}