User Tools

Site Tools


cplusplus:pointers_4_slides

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
Next revisionBoth sides next revision
cplusplus:pointers_4_slides [2019/03/31 22:08] mithatcplusplus:pointers_4_slides [2021/10/24 03:01] – [Deallocating arrays] mithat
Line 10: Line 10:
  
 ===== 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+  * **Dynamic memory allocation** allows you to reserve blocks of computer memory at //runtime//
-  * Happens at runtime.+  * Typically used with pointers.
  
-===== The ''new'' operator ===== +===== The new operator ===== 
-  * ''new <data-type>'' reserves a block of memory to hold the specified %%<data-type>%% and returns the base address of that block:+  * ''new <data-type>'' 
 +    * reserves a block of memory to hold the specified %%<data-type>%% 
 +    * returns the base address of that block
 +    * optional parenthesis around ''<data-type>''
  
 <code cpp> <code cpp>
Line 23: Line 26:
 </code> </code>
  
-  * ''foo'' points to a ''double'' that is //not// a variable.+  * ''foo'' points to a ''double'' that isn't associated with a variable identifier.
  
 ===== Example ===== ===== Example =====
Line 36: Line 39:
     double *myPtr, *yourPtr;     double *myPtr, *yourPtr;
  
-    myPtr = new (double)+    myPtr = new double; 
-    yourPtr = new (double);+    yourPtr = new double;
  
     cout << "Enter a number: ";     cout << "Enter a number: ";
Line 50: Line 53:
 </file> </file>
  
-==== Dynamic allocation of arrays ====+===== Dynamic allocation of arrays =====
  
-Dynamic memory allocation can be used to allocate an array:+  * Dynamic memory allocation can be used to allocate an array
 +  * WarningIf there is not enough memory available to allocate the desired block, BadThings™ will happen.
  
 <file cpp dynamic-array.cpp> <file cpp dynamic-array.cpp>
Line 79: Line 83:
 } }
 </file> </file>
- 
-If there is not enough memory available to allocate the desired block, BadThings™ will happen. 
  
 ===== Memory Management ===== ===== Memory Management =====
  
-==== Memory management of regular variables ==== +===== Memory management of regular variables ===== 
-Regular local variables are destroyed when the lifetime of the scope where they are declared ends. In the example below, ''localVar'' is destroyed at the end of the function call along with the storage associated with it:+ 
 +  * The management of memory associated with regular local variables is automatic. 
 +  * Regular local variables are destroyed when the lifetime of the scope where they are declared ends.
  
 <file cpp local-var-memory.cpp> <file cpp local-var-memory.cpp>
Line 105: Line 109:
 void ninetynine() void ninetynine()
 { {
-    int localVar = 99;+    int localVar = 99;  // localVar is destroyed at end of fcn call
     cout << localVar << endl;     cout << localVar << endl;
 } }
 </file> </file>
  
-Thus, the management of memory associated with regular local variables is automatic.+===== Memory management of dynamically allocated storage =====
  
-==== Memory management of dynamically allocated storage ==== +  * Dynamically allocated memory is //not// automatically managed. 
-Dynamically allocated memory is //not// automatically managed in C++In the example below, the variable ''localPtr'' is destroyed at the end of the function call, but the dynamically allocated storage for the ''int'' pointed to by ''localPtr'' is not.+  * Below, the variable ''localPtr'' is destroyed at the end of the function call, but the dynamically allocated storage for the ''int'' pointed to by ''localPtr'' is not.
  
 <file cpp memory-loss.cpp> <file cpp memory-loss.cpp>
Line 135: Line 139:
 void ninetynine() void ninetynine()
 { {
-    int *localPtr = new int;+    int *localPtr = nullptr;  // localPtr is destroyed at end of fcn call 
 +    localPtr = new int;       // but not dynamically allocated storage
  
     *localPtr = 99;     *localPtr = 99;
Line 141: Line 146:
 } }
 </file> </file>
- 
-Because the pointer is the only way to access the allocated block, there is no way to do anything useful with the block after the function terminates and main enters the ''// ... do some other stuff ... //'' part of the program. The dynamically allocated memory block is still taking up space, and there's no way to make another pointer to point to that block. 
  
 ==== Memory leaks ==== ==== Memory leaks ====
-The above is an example of a **memory leak**. It's a tiny onewhen the program is run, it uses 4 or 8 or whatever (i.e., ''sizeof(int)'') more bytes of RAM after the function returns than it needs to. This may seem like nothing worth losing sleep over, but what if ''ninetynine()'' appears in a loop or is otherwise executed repeatedly?+ 
 +  * The previous is an example of a small **memory leak**. 
 +  * A bigger leak:
  
 <file cpp memory-leak.cpp> <file cpp memory-leak.cpp>
Line 175: Line 180:
 </file> </file>
  
-This adds up to a lot of wasted RAM. Memory leaks, no matter how small, are considered bad programming practice. Fortunately, they can be fixed by the proper use of //deallocation//.+===== Memory leaks =====
  
-==== Deallocation ==== +  * Memory leaks, no matter how small, are bad programming practice. 
-**Deallocation** is the process of releasing back to the OS storage that was previously dynamically allocated. +  Can be fixed by the proper use of **deallocation**: releasing back to the OS storage that was previously dynamically allocated.  
 +  * **Deallocation of dynamically allocated storage does not happen automatically.** 
 +    * You must explicitly (i.e., manually) deallocate the memory.
  
-Deallocation of dynamically allocated storage does not happen automatically in C++, therefore you must explicitly (i.e., manually) deallocate the memory. The ''delete'' operator lets you explicitly deallocate memory that has been dynamically allocated.+===== The delete operator ===== 
 +  * The ''delete'' operator lets you explicitly deallocate memory that has been dynamically allocated.
  
-<WRAP center round tip 90%+<code cpp
-Any memory that you have dynamically allocated must be deallocated somewhere in the program. Otherwise memory leak will result+int *myPtr = new int; 
-</WRAP>+... 
 +delete myPtr; // deallocates block pointed to by myPtr. 
 +</code> 
 + 
 +  * Principle: All dynamically allocated memory must be deallocated somewhere in the program. 
 +    * "For every ''new'' ''delete''." 
 + 
 +===== Example =====
  
 The code below fixes the memory leak introduced above: The code below fixes the memory leak introduced above:
Line 212: Line 227:
 </file> </file>
  
-To deallocate dynamically allocated arrays, use square brackets: ''delete [] arrayPtr;''+===== Deallocating arrays ===== 
 + 
 +Use square brackets to deallocate dynamically allocated arrays: ''delete [] arrayPtr;''
  
 <file cpp Gaddis-Pr9-14.cpp> <file cpp Gaddis-Pr9-14.cpp>
Line 224: Line 241:
 int main() int main()
 { {
-    double *sales = nullptr, // 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 271: Line 288:
 ===== heap vs. stack ===== ===== heap vs. stack =====
  
-  * Local variables and dynamically allocated storage come from different pools of RAM.+  * Local variables and dynamically allocated storage come from pools of RAM.
   * **stack**: a pool of memory whose allocation and deallocation is automatically managed.   * **stack**: a pool of memory whose allocation and deallocation is automatically managed.
     * Local and global variables are allocated from the stack.     * Local and global variables are allocated from the stack.
cplusplus/pointers_4_slides.txt · Last modified: 2021/10/24 03:02 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki