Question: Instructions: Consider the following C + + program. It asks the user for the sizes of two dynamic arrays, and initializes these arrays to contain
Instructions:
Consider the following C program. It asks the user for the sizes of two dynamic arrays, and initializes these arrays to contain the values and respectively.
Include statements
#include
#include
using namespace std;
Main function
int main
Get user input
int size;
cout "Enter size of array:
;
cin size;
if size
size;
Get user input
int size;
cout "Enter size of array:
;
cin size;
if size
size;
Process array
int array new intsize;
cout "array:
;
for int i ; i size; i
arrayi;
cout arrayi;
cout endl;
Location A
Process array
int array new intsize;
cout "array:
;
for int i ; i size; i
arrayi;
cout arrayi;
cout endl;
Location B
Location C
return ;
Step : Copy this program into your C program editor, and compile it Hopefully you will not get any error messages. Run the program with a variety of input values to see what it prints. You should see a lot of s and s printed on the screen.
Step : It is very important to return memory to the operating system when you are finished working with it Otherwise, your program will have a "memory leak" and it may die if it runs out of memory. Edit your program and add the following code at "Location A in the program.
Return memory to OS
delete array;
Step : Compile and run your program. It should print out the same information as before. Since we are releasing the memory for array before we are allocating array there is some chance that the OS will reuse some or all of array memory for array To see if this is true, you can edit the body of the array print loop as follows:
cout arrayi;
arrayi;
Step : Recompile and run your program with size size Then try size size Finally try size size You should see that in some cases the initial values of array are equal to zero, and in other cases they are equal to the values we stored in array proving the memory has been reused.
Step : In step we returned the array memory back to the OS Since we have not changed this pointer, it still points to the original chunk of memory we allocated at the top of the program. For this reason, array is called a dangling reference it points to memory that was valid at one time, but the OS thinks this pointer is no longer in use. To see what is now in in array add the following code at "Location B in the program.
Print array
cout "array:
;
for int i ; i size; i
cout arrayi;
cout endl;
Step : Recompile and run your prog
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
