User Tools

Site Tools


cplusplus:pointers_4

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
cplusplus:pointers_4 [2016/03/21 22:23] – [Deallocation] mithatcplusplus:pointers_4 [2019/03/31 22:35] (current) mithat
Line 1: Line 1:
 ====== Pointers 4 ====== ====== Pointers 4 ======
  
-Dynamic memory, memory management, pointers as return types. +Dynamic memory, memory management, pointers as return types.((Portions adapted from: 
- +Gaddis, Tony. "Pointers." In //Starting Out with C++: From Control Structures through Objects//. 8th ed. Boston: Pearson, 2015. 495-546.))
-<WRAP center round important 60%> +
-This content has not been vetted for C++11 compliance. +
-</WRAP>+
  
 ===== Dynamic memory allocation ===== ===== Dynamic memory allocation =====
-**Dynamic memory allocation** allows you to reserve blocks of computer memory for use as storage but without associating a variable name with it. This allocation happens at runtime, hence the term //dynamic// memory allocation. It is used most often used with pointers.+**Dynamic memory allocation** allows you to reserve blocks of computer memory at //runtime// and use them to store variable data. The declared blocks or memory are most often used with pointers.
  
 ==== The ''new'' operator ==== ==== The ''new'' operator ====
Line 20: Line 17:
 </code> </code>
  
-''foo'' now points to a ''double'' that is //not// a variable.+''foo'' now points to a ''double'' that is not associated with regular variable identifier.
  
 <file cpp simple-allocation.cpp> <file cpp simple-allocation.cpp>
Line 175: Line 172:
 **Deallocation** is the process of releasing back to the OS storage that was previously dynamically allocated.  **Deallocation** is the process of releasing back to the OS storage that was previously dynamically allocated. 
  
-//Any memory that has been dynamically allocated must be deallocated (i.e., released back to the OSsomewhere in the program, otherwise a memory leak will result.// +Deallocation of dynamically allocated storage does not happen automatically in C++, therefore you must explicitly (i.e., manuallydeallocate the memory. The ''delete'' operator lets you explicitly deallocate memory that has been dynamically allocated.
  
-Since deallocation of dynamically allocated storage does not happen automatically in C++, you must explicitly (i.e., manually) deallocate the memoryThe ''delete'' operator lets you explicitly deallocate memory that has been dynamically allocated.+<WRAP center round tip 90%> 
 +Any memory that you have dynamically allocated must be deallocated somewhere in the programOtherwise a memory leak will result. 
 +</WRAP>
  
 The code below fixes the memory leak introduced above: The code below fixes the memory leak introduced above:
Line 217: Line 216:
 int main() int main()
 { {
-    double *sales, // To dynamically allocate an array +    double *sales = nullptr, // To dynamically allocate an array 
-    total = 0.0,   // Accumulator +    total = 0.0, // Accumulator 
-    average;       // To hold average sales +    average; // To hold average sales 
-    int numDays,   // To hold the number of days of sales +    int numDays, // To hold the number of days of sales 
-        count;     // Counter variable +        count; // Counter variable
  
     // Get the number of days of sales.     // Get the number of days of sales.
Line 257: Line 255:
     // Free dynamically allocated memory     // Free dynamically allocated memory
     delete [] sales;     delete [] sales;
-    sales = 0; // Make sales point to null.+    sales = nullptr; // Make sales a nullptr.
  
     return 0;     return 0;
-}+
 </file> </file>
  
 ==== heap vs. stack ==== ==== heap vs. stack ====
  
-Up to now, we may have given the impression that local variables and dynamically allocated storage are both allocated memory from the same amorphous pool of RAM. This is not the case. The **stack** is a pool of memory whose allocation and deallocation is automatically managed. Local variables (and global ones too) are allocated from the stack. The **heap** is a pool of memory whose allocation and deallocation is explicitly (i.e., manually) managed. Dynamically allocated memory are allocated from the heap.+Local variables and dynamically allocated storage come from different pools of RAM. The **stack** is a pool of memory whose allocation and deallocation is automatically managed. Local variables (and global ones too) are allocated from the stack. The **heap** is a pool of memory whose allocation and deallocation is explicitly managed. Dynamically allocated storage is allocated from the heap.
  
 A more detailed discussion of the heap versus the stack, while important, is beyond the scope of the present discussion. But it is important to know that there are two different memory pools that C++ programs draw from. A more detailed discussion of the heap versus the stack, while important, is beyond the scope of the present discussion. But it is important to know that there are two different memory pools that C++ programs draw from.
 +
 ==== ''malloc'' and ''free'' ==== ==== ''malloc'' and ''free'' ====
 ''malloc'' and ''free'' can also used be used to allocate and deallocate storage. They are part of C and so are available in C++ as well. However, they are more cumbersome than ''new'' and ''delete'' introduced in C++, and their use is discouraged. ''malloc'' and ''free'' can also used be used to allocate and deallocate storage. They are part of C and so are available in C++ as well. However, they are more cumbersome than ''new'' and ''delete'' introduced in C++, and their use is discouraged.
Line 345: Line 344:
 int *getRandomNumbers(int num) int *getRandomNumbers(int num)
 { {
-   int *arr;    // Array to hold the numbers+   int *arr = nullptr; // Array to hold the numbers
        
    // Return null if num is zero or negative.    // Return null if num is zero or negative.
Line 367: Line 366:
 </file> </file>
  
 +===== Smart Pointers =====
 +C++11's //smart pointers// manage their own memory to help mitigate memory leaks. To use smart pointers, you need to ''#include <memory>''.
 +
 +One smart pointer is the ''unique_ptr'':
 +
 +''**unique_ptr<**//type_pointed_to//**>** //pointer_name//**(** //expression_to_allocate_memory// **)**''
 +
 +<file c++ Gaddis-Pr9-17.cpp>
 +// This program demonstrates a unique_ptr.
 +#include <iostream>
 +#include <memory>
 +using namespace std;
 +
 +int main() 
 +{
 +   // Define a unique_ptr smart pointer, pointing
 +   // to a dynamically allocated int.
 +   unique_ptr<int> ptr( new int );
 +
 +   // Assign 99 to the dynamically allocated int.
 +   *ptr = 99;
 +
 +   // Display the value of the dynamically allocated int.
 +   cout << *ptr << endl;
 +   return 0;
 +}
 +</file>
 +
 +''ptr'' will be automatically deleted when the function returns.
 +
 +Dynamically allocating a large block of managed memory is demonstrated here:
 +
 +<file c++ Gaddis-Pr9-18.cpp>
 +// This program demonstrates a unique_ptr pointing
 +// to a dynamically allocated array of integers.
 +#include <iostream>
 +#include <memory>
 +using namespace std;
 +
 +int main() 
 +{
 +   int max;   // Max size of the array
 +
 +   // Get the number of values to store.
 +   cout << "How many numbers do you want to enter? ";
 +   cin >> max;
 +   
 +   // Define a unique_ptr smart pointer, pointing
 +   // to a dynamically allocated array of ints.
 +   unique_ptr<int[]> ptr( new int[max]);
 +
 +   // Get values for the array.
 +   for (int index = 0; index < max; index++)
 +   {
 +      cout << "Enter an integer number: ";
 +      cin >> ptr[index];
 +   }
 +
 +   // Display the values in the array.
 +   cout << "Here are the values you entered:\n";
 +   for (int index = 0; index < max; index++)
 +      cout << ptr[index] << endl;
 +
 +   return 0;
 +}
 +</file>
 +
 +Other smart pointers are ''weak_ptr'' and ''shared_ptr''. They won't be covered here.
cplusplus/pointers_4.1458599011.txt.gz · Last modified: 2016/03/21 22:23 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki