In: Computer Science
Consider the following program. There are 11 statements in the program starting with int x; Show the memory allocated for the program in the stack and heap for each statement. Also, show any values assigned to each of these memory locations. In other words, you will show 11 stacks and 11 heaps as the answer to your question.
#include <iostream>
using namespace std;
int main() {
int x; // Stmt 1
int * y; // Stmt 2
y = new int; // Stmt 3
*y = 10; // Stmt 4
int * z; // Stmt 5
z = new int[5]; // Stmt 6
z[0] = 15; // Stmt 7
*(z + 1) = 20; // Stmt 8
delete y; // Stmt 9
y = z; // Stmt 10
delete [] z; // Stmt 11
return 0;
}
Note : New keyword is used to dynamically allocate memory in heap in C++, and delete keybord is used to free this memory from heap.
Lets see what happens for each statement :
int x; // Stmt 1
will contain some garbage value.
int * y; // Stmt 2
y = new int; // Stmt 3
*y = 10; // Stmt 4
int * z; // Stmt 5
z = new int[5]; // Stmt 6
z[0] = 15; // Stmt 7
*(z + 1) = 20; // Stmt 8
delete y; // Stmt 9
y = z; // Stmt 10
delete [] z; // Stmt 11
Like, if this helped :)