Dynamic Data and a Dynamic Array
- Parts of this are from chapter 14.
- Parts of this are not.
- Data in most programs are stored in two places
- Static data is stored on the stack.
- Dynamic data is stored on the heap.
- The compiler manages the stack.
- The user manages (partially) the heap.
- Storage space on the heap
- Is allocated with a call to new
- Is released with a call to delete.
- new
-
ptrVar = new type
-
ptrVar = new type[int size]
- For basic data types this function
- Allocates memory on the heap
- Returns a pointer to this memory.
- For classes
- It calls the constructor as well.
- For the array version it will call the constructor many times.
- If there is no memory available, it will throw an exception.
- delete
-
delete ptrVar
-
delete [] ptrVar
- This will return the memory to the free store (heap)
- If the memory contains a class, the destructor will be called.
- THIS DOES NOT CHANGE THE VALUE OF ptrVar
- You can only delete memory once.
- You must match new [] and delete [] , new and delete
- A Memory Leak is the loss of memory space that occurs when dynamic data is allocated but not deallocated.
- This is an attention to detail problem.
- This is huge.
- If you allocate memory, later you must deallocate it.
- A dangling pointer is a pointer to memory that has been deallocated.
- An inaccessible object is dynamic memory that has not been deleted but has not pointer pointing to it.
- All three of these are common errors.
- There are structures to handle them in modern c++
- But we need at least a basic understanding of raw pointers.