Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dynamic Memory Allocation

Similar presentations


Presentation on theme: "Dynamic Memory Allocation"— Presentation transcript:

1 Dynamic Memory Allocation
9.8 Dynamic Memory Allocation

2 Dynamic Memory Allocation
Can allocate storage for a variable while program is running Computer returns address of newly allocated variable Uses new operator to allocate memory: double *dptr = nullptr; dptr = new double; new returns address of memory location 2

3 Dynamic Memory Allocation
Can also use new to allocate array: const int SIZE = 25; arrayPtr = new double[SIZE]; Can then use [] or pointer arithmetic to access array: for(i = 0; i < SIZE; i++) *arrayptr[i] = i * i; or *(arrayptr + i) = i * i; Program will terminate if not enough memory available to allocate 3

4 Releasing Dynamic Memory
Use delete to free dynamic memory: delete fptr; Use [] to free dynamic array: delete [] arrayptr; Only use delete with dynamic memory! 4

5 Dynamic Memory Allocation in Program 9-14

6 Dynamic Memory Allocation in Program 9-14
Program 9-14 (Continued)

7 Dynamic Memory Allocation in Program 9-14
Program 9-14 (Continued) Notice that in line 49 nullptr is assigned to the sales pointer. The delete operator is designed to have no effect when used on a null pointer.

8 Returning Pointers from Functions
9.9 Returning Pointers from Functions

9 Returning Pointers from Functions
Pointer can be the return type of a function: int* newNum(); The function must not return a pointer to a local variable in the function. A function should only return a pointer: to data that was passed to the function as an argument, or to dynamically allocated memory 9

10 From Program 9-15

11 Using Smart Pointers to Avoid Memory Leaks
9.10 Using Smart Pointers to Avoid Memory Leaks

12 Using Smart Pointers to Avoid Memory Leaks
In C++ 11, you can use smart pointers to dynamically allocate memory and not worry about deleting the memory when you are finished using it. Three types of smart pointer: Must #include the memory header file: In this book, we introduce unique_ptr: unique_ptr shared_ptr weak_ptr #include <memory> unique_ptr<int> ptr( new int );

13 Using Smart Pointers to Avoid Memory Leaks
The notation <int> indicates that the pointer can point to an int . The name of the pointer is ptr . The expression new int allocates a chunk of memory to hold an int. The address of the chunk of memory will be assigned to ptr.

14 Using Smart Pointers in Program 9-17


Download ppt "Dynamic Memory Allocation"

Similar presentations


Ads by Google