MemoryManagement.md (1440B)
1 # Memory Management 2 3 Memory management CS 202 ~W10 C++ 4 5 Memory management in C++ is done using a few keywords shown below 6 7 **delete:** The delete keyword deallocates the memory associated with an object on the heap. 8 9 **new:** The new keyword specifies to create an object on the heap. This will not be deallocated when no longer referenced so it needs to be deleted when the time comes. 10 11 \*: The asterisk is used to create a pointer. The pointer will be of a type and can be assigned to a variable. 12 13 **&:** The ampersand, known as the address operator, is used to take the address of a variable. An example of this is as follows where we assign a pointer to point to the location of an integer: 14 15 ```cpp 16 17 int var{3000}; 18 int *ptr; 19 ptr = &var; 20 21 ``` 22 23 **Referencing:** This is done by the & (see above as this is quite simple). 24 25 **Dereferencing:** This is done by the * character. This gives access to the underlying values. This can be used to both assign the underlying variable(s) and also to assign other things to them. Below is an example: 26 27 ```cpp 28 29 int x{100}; 30 int * ptr = &x; 31 cout << *ptr; 32 //reassigns x to 1000. 33 *ptr = 1000; 34 35 //these print the same value, 1000 36 cout << *ptr; 37 cout << x; 38 ``` 39 40 A few cases of memory management in action are [SinglyLinkedList](SinglyLinkedList.md) and [[DoublyLinkedList.md]] which both require memory management to ensure nodes in the heap are not lost after removing a node from the list.