Dynamic Memory
- We are about to discuss raw pointers
- While not essential, I think it is important to understand how these work.
- They are the basic data structure for this section.
- They are available in c, c++ and some other languages.
- They are so dangerous that they are not available in python, java, javascript and other languages.
- Later you will lean about smart pointers.
- These are a part of c++
- They are a safer version of pointers.
- All memory we have used so far has been statically allocated memory.
- This is not strictly true, it is allocated at run time, but
- The size is known by the compiler
- And it is most likely allocated off of the stack.
- The compiler is responsible for managing this memory.
- We are about to start allocating memory at run time.
- This is called dynamic memory.
- It is allocated off of the stack.
- And we are responsible for managing this memory.
- We need a new data type, a pointer.
- This is just an address.
- But it is better to think of it as a pointer.
- It points to somewhere else.
- Declaring a pointer
-
type * identifier
- If you have multiple identifiers, the * needs to be repeated
-
type * id1, * id2, * id3;
- nullptr
- what is
string::npos
?
- Just like this, a null pointer points to nothing.
- Historically there have been three representations for a null pointer.
- 0 - in the C days. Don't use this.
-
NULL
in the later C days and early C++, don't use this.
-
nullptr
in c++11, use this.
- FOR NOW YOU MUST, even though I will forget
- Initialize to nullptr when you declare it.
- int * intPtr{nullptr};
- WordT * wordPtr{nullptr};
- Allocating memory
- If you are allocating a single instance of an object.
-
ptr = new type
-
wordPtr = new WordT;
-
new
is actually an operator like +, and, or ==
- New can be used to allocate an array of objects as well
-
ptr = new type[positive integer]
-
wordArrayPtr = new WordT[newSize];
- When memory is allocated, it also must be freed.
- This is done with the delete operator.
-
delete intPtr;
-
delete[] intAry;
- You must use a delete that matches your new.
- A memory leak is a bug where memory is allocated but not never deallocated.
- This can cause a problem over time as you will have the heap and the stack collide.
- A inaccessible object is memory that has been allocated and no longer has a pointer pointing to it.
- A dangling pointer occurs when the programmer thinks the pointer is pointing to a valid object, but it is not. Usually following a delete.