Question

Introduction: One of the most important uses of pointers is for dynamic allocation of memory. In...

Introduction:

One of the most important uses of pointers is for dynamic allocation of memory. In C++ there are commands that let the user request a chunk of memory from the operating system, and use this memory to store data. There are also commands to return memory back to the O/S when the program is finished using the data. In this lab, we will explore some of the things that can go wrong when using dynamic memory and discuss how to avoid these problems.

As you saw in the previous lab, we there are five steps we must follow 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 the sizes of two dynamic arrays, and initializes these arrays to contain the values 17 and 42 respectively.

// Include statements
#include <cstdlib>
#include <iostream>
using namespace std;

// Main function
int 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++ 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 17's and 42's printed on the screen.

Step 2: 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 O/S
   delete [] array1;

Step 3: Compile and run your program. It should print out the same information as before. Since we are releasing the memory for array1 before we are allocating array2 there is some chance that the O/S will reuse some or all of array1 memory for array2. To see if this is true, you can edit the body of the array2 print loop as follows:

      cout << array2[i] << " ";
      array2[i] = 42;

Step 4: Recompile and run your program with size1=20, size2=40. Then try size1=20, size2=20. Finally try size1=40, size2=20. You should see that in some cases the initial values of array2 are equal to zero, and in other cases they are equal to the values we stored in array1, proving the memory has been reused.

Step 5: In step 2 we returned the array1 memory back to the O/S. 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, array1 is called a dangling reference -- 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 is now in in array1, add the following code at "Location B" in the program.

   // Print array1
   cout << "array1:\n";
   for (int i = 0; i < size1; i++)
      cout << array1[i] << " ";
   cout << endl;

Step 6: Recompile and run your program with size1=20, size2=40. Then try size1=20, size2=20. Finally try size1=40, size2=20. You should see that in some cases the initial values of array1 are unchanged, and in other cases they are equal to the values we stored in array2. In practice it is a very bad idea to use dangling references, because the odds are high that the original data will be changed.

Step 7: It is considered the be a "good programming practice" to set the pointer variable to NULL after you return the dynamic memory. This will prevent programmers from accidentally using a dangling reference later in the program. To see how this works, add the following code at "Location C" in the program.

   // 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 with size1=20, size2=20. What does your program output now? You should see "Segmentation fault (core dumped)" which is one of the oldest run time error messages. You will see this message whenever you attempt to access memory using a pointer that is equal to NULL. In this case, the error occurs when we attempt to use array1[i] inside the for loop. Debugging run time errors like this can be a pain sometimes, but they are almost always easier to find than subtle run time errors caused by incorrectly using dangling references. To fix this code, remove all of the code you added in Step 7 except the "array1 = NULL;" line.

Step 9: Edit your program one last time, and add the following code just before the return statement. This is the preferred method for returning memory to the O/S and preventing dangling references in C++. In future, you should use this pair of lines together when you release dynamic memory.

   // Return memory to O/S
   delete [] array2;
   array2 = NULL;

Step 9: Compile your program one last time, and upload your code into the auto grader by following the instructions below.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

If you have any doubts, please give me comment...

// Include statements

#include <cstdlib>

#include <iostream>

using namespace std;

// Main function

int 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

// Return memory to O/S

delete[] array1;

// 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

// Print array1

cout << "array1:\n";

for (int i = 0; i < size1; i++)

cout << array1[i] << " ";

cout << endl;

// Location C

// Print array1

array1 = NULL;

cout << "array1:\n";

for (int i = 0; i < size1; i++)

cout << array1[i] << " ";

cout << endl;

// Return memory to O/S

delete[] array2;

array2 = NULL;

return 0;

}

Add a comment
Know the answer?
Add Answer to:
Introduction: One of the most important uses of pointers is for dynamic allocation of memory. In...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Programs written in a language that supports pointers and dynamic memory allocation can suffer from dangling...

    Programs written in a language that supports pointers and dynamic memory allocation can suffer from dangling pointers and lost heap-dynamic variables (or garbages). (a) A dangling pointer is a pointer that contains the address of a piece of memory that no longer belongs to the program. Give one scenario that can cause dangling pointers. Support your scenario with sample codes in your favorite language. Poorly implemented languages leave the detection of the dangling pointer problem to the operating system. Suggest...

  • c++ please no global varaible write a value returning function input data to dynamically allocate a...

    c++ please no global varaible write a value returning function input data to dynamically allocate a short array of size elements and store the input data entered from the disk file into array.Return the base address of the array allocated.Read the data from the text file Hello.txt and store the data in reverse order in the array.the size of the data set will be in the file size 10 and the data was 1 2 3 4 5 6 7...

  • So. I'm sick and I need help figuring out whatever is going on with this. #include...

    So. I'm sick and I need help figuring out whatever is going on with this. #include using namespace std; //prototypes int getExchangesInBubbleSort(int[], int); int getExchangesInSelectionSort(int[], int); int main() {    char choice;       cout << "1. Search Benchmarks\n";    cout << "2. Sorting Benchmarks\n";    do    {        int input;        cout << "Please enter the program you would like to run. \n";        cin >> input;               if (input == 1)...

  • Lab 10A Measure the program execution time One easy way to measure the program execution time is ...

    Lab 10A Measure the program execution time One easy way to measure the program execution time is encapsulate the useful timing functionality of C++ chrono library, This is illustrated inhttps://www.learncpp.com/cpp-tutorial/8-16-timing-your-code/ The example usingChronoTimer.cpp (Github/m10) is an example program using this chrono Timer class object to measure the Sorting on on an integer array of 10000 random integers based on the Bubble Sort vs. the C++ built-in Sort (an https://www.quora.com/Which-sorting-algorithm-does-STL-standard-template-library-use-in-c++. ) Please measure the performance of sorting the same array used...

  • C++ problem with dynamic arrays is that once the array is created using the new operator...

    C++ problem with dynamic arrays is that once the array is created using the new operator the size cannot be changed. For example, you might want to add or delete entries from the array similar to the behavior of a vector. This project asks you to create a class called DynamicStringArray that includes member functions that allow it to emulate the behavior of a vector of strings. The class should have: A private member variable called dynamicArray that references a...

  • Lanuage C++ (Beginner level) Please...I need help with this assignment If I still have question, can...

    Lanuage C++ (Beginner level) Please...I need help with this assignment If I still have question, can i contact you? -------------------------- Program 1 - WRITE ALL THE CODE in ONE FILE...   MyArrayPtrArith1.cpp Step 1 - Define the class Write a class, myArrayClass, that creates an integer array. * Add an 'arraySize' variable, initialize to zero ( default constructor function ) * Create int * ptrArray ( default constructor set to NULL ) * Add a default constructor ( see above for...

  • Problem 6(15 Points) MARIE Assembly Programming Develop a MARIE program containing a main function which finds the smallest element of an array T is shown below. The passing arguments and one sub...

    Problem 6(15 Points) MARIE Assembly Programming Develop a MARIE program containing a main function which finds the smallest element of an array T is shown below. The passing arguments and one subroutine function called Sindmin findmin function array and the aro the findmin subroutine functon are the beginning e pseudo code for the subroutine elements of Array1 and Arra array size Continue the following MARIE program to find the smallest ORG 100 Jump Start nt findmin (int "addr, int size)...

  • C++ Please ensure code is fully working, will rate Question to be answered:    Repeat Exercise...

    C++ Please ensure code is fully working, will rate Question to be answered:    Repeat Exercise 1 for the class linkedStackType question one:        Two stacks of the same type are the same if they have the same number of elements and their elements at the corresponding positions are the same. Overload the relational operator == for the class stackType that returns true if two stacks of the same type are the same, false otherwise. Also, write the definition...

  • Multiple Choice Multiple Choice Section 4.1 Pointers and Dynamic Memory Consider the following statements: int *p;...

    Multiple Choice Multiple Choice Section 4.1 Pointers and Dynamic Memory Consider the following statements: int *p; int i; int k; i = 42; k = i; p = &i; After these statements, which of the following statements will change the value of i to 75? A. k = 75; B. *k = 75; C. p = 75; D. *p = 75; E. Two or more of the answers will change i to 75. Consider the following statements: int i =...

  • 1. Your project will include the following three files: A header file: dynamicArray.h that includes a...

    1. Your project will include the following three files: A header file: dynamicArray.h that includes a list of function prototypes as enumerated in the next section. An implementation file: dynamicArray.cpp that implements the functions declared in the header file. A test driver file: dynamicArray-main.cpp that includes the main() function so that you can test all the functions you've implemented above. 2. The header file dynamicArray.h will include the following list of functions: constructing a dynamic array of the specified size...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT