[Solved] One Important Uses Pointers Dynamic Allocation Memory C Commands Let User Request Chunk Me Q37227932
One of the most important uses of pointers is for dynamicallocation of memory. In C++ there are commands that let the userrequest a chunk of memory from the operating system, and use thismemory to store data. There are also commands to return memory backto the O/S when the program is finished using the data. In thislab, we will explore some of the things that can go wrong whenusing dynamic memory and discuss how to avoid these problems.
As you saw in the previous lab, we there are five steps we mustfollow when using dynamic variables:
- Declare a pointer variable of the desired data type
- Use the “new” command to request memory
- Make use of the memory in the program
- Use the “delete” command to return memory
- Set the pointer variable to NULL
Instructions:
Consider the following C++ program. It asks the user for thesizes of two dynamic arrays, and initializes these arrays tocontain the values 17 and 42 respectively.
// Include statements#include <cstdlib>#include <iostream>using namespace std;// Main functionint main(){ // Get user input int size1 = 0; cout << “Enter size of array1:n”; cin >> size1; if (size1 < 0) size1 = 0; // Get user input int size2 = 0; cout << “Enter size of array2:n”; cin >> size2; if (size2 < 0) size2 = 0; // Process array1 int * array1 = new int[size1]; cout << “array1:n”; for (int i = 0; i < size1; i++) { array1[i] = 17; cout << array1[i] << ” “; } cout << endl; // Location A // Process array2 int * array2 = new int[size2]; cout << “array2:n”; for (int i = 0; i < size2; i++) { array2[i] = 42; cout << array2[i] << ” “; } cout << endl; // Location B // Location C return 0 ;}
Step 1: Copy this program into your C++ programeditor, and compile it. Hopefully you will not get any errormessages. Run the program with a variety of input values to seewhat it prints. You should see a lot of 17’s and 42’s printed onthe screen.
Step 2: It is very important to return memoryto the operating system when you are finished working with it.Otherwise, your program will have a “memory leak” and it may die ifit runs out of memory. Edit your program and add the following codeat “Location A” in the program.
// Return memory to O/S delete [] array1;
Step 3: Compile and run your program. It shouldprint out the same information as before. Since we are releasingthe memory for array1 before we are allocating array2 there is somechance that the O/S will reuse some or all of array1 memory forarray2. To see if this is true, you can edit the body of the array2print loop as follows:
cout << array2[i] << ” “; array2[i] = 42;
Step 4: Recompile and run your program withsize1=20, size2=40. Then try size1=20, size2=20. Finally trysize1=40, size2=20. You should see that in some cases the initialvalues of array2 are equal to zero, and in other cases they areequal to the values we stored in array1, proving the memory hasbeen reused.
Step 5: In step 2 we returned the array1 memoryback to the O/S. Since we have not changed this pointer, it stillpoints to the original chunk of memory we allocated at the top ofthe program. For this reason, array1 is called a danglingreference — it points to memory that was valid at one time,but the O/S thinks this pointer is no longer in use. To see what isnow in in array1, add the following code at “Location B” in theprogram.
// Print array1 cout << “array1:n”; for (int i = 0; i < size1; i++) cout << array1[i] << ” “; cout << endl;
Step 6: Recompile and run your program withsize1=20, size2=40. Then try size1=20, size2=20. Finally trysize1=40, size2=20. You should see that in some cases the initialvalues of array1 are unchanged, and in other cases they are equalto the values we stored in array2. In practice it is a very badidea to use dangling references, because the odds are highthat the original data will be changed.
Step 7: It is considered the be a “goodprogramming practice” to set the pointer variable to NULL after youreturn the dynamic memory. This will prevent programmers fromaccidentally using a dangling reference later in the program. Tosee how this works, add the following code at “Location C” in theprogram.
// Print array1 array1 = NULL; cout << “array1:n”; for (int i = 0; i < size1; i++) cout << array1[i] << ” “; cout << endl;
Step 8: Recompile and run your program withsize1=20, size2=20. What does your program output now? You shouldsee “Segmentation fault (core dumped)” which is one of the oldestrun time error messages. You will see this message whenever youattempt to access memory using a pointer that is equal to NULL. Inthis case, the error occurs when we attempt to use array1[i] insidethe for loop. Debugging run time errors like this can be a painsometimes, but they are almost always easier to find than subtlerun time errors caused by incorrectly using dangling references. Tofix this code, remove all of the code you added in Step 7 exceptthe “array1 = NULL;” line.
Step 9: Edit your program one last time, andadd the following code just before the return statement. This isthe preferred method for returning memory to the O/S and preventingdangling references in C++. In future, you should use this pair oflines together when you release dynamic memory.
// Return memory to O/S delete [] array2; array2 = NULL;
Step 9: Compile your program one last time, andupload your code into the auto grader by following the instructionsbelow.
Expert Answer
Answer to One of the most important uses of pointers is for dynamic allocation of memory. In C++ there are commands that let the u… . . .
OR

