Tuesday
Agenda
- Pointers
- Method Stack Diagram
- Dynamic Memory
- Debugging tools: Valgrind and GDB
Pointers
- All variables in your program are stored at a specific location in memory. These 'locations' in memory are called memory addresses.
- A pointer is a variable that contains a memory address. We usually depict them with an arrow pointing to the variable or object whose address they store.
- There are two operators related to pointers in C++:
- The
&
operator, called address of operator, returns the address of any variable.
You can think of it as the "give me an arrow to" operator.
- The
*
operator, called dereference operator, returns the value at the address stored by a pointer variable, or refers to the box at that address.
You can think of it as the "follow the address of" operator.
- In C++, the type of a pointer depends on the type of the variable or object it points to. We denote the type of the pointer by adding a star (
*
) to the type of variable or object it points to.
For example, int*
is a pointer to an int
, string*
is a pointer to a string
, int**
is a pointer to a pointer to an int, etc.
-
nullptr
is a special value we assign to a pointer to signify that the pointer is pointing nowhere. Dereferencing a nullptr
results in a memory error.
- When dynamically allocating memory (see next topic),
new
returns a pointer type
- Accessing an attribute variable from a pointer to an object:
(*p).getX()
? Yuck
p->getX()
? OK.
- More examples with the Point class.
Dynamic Memory
- Static data
- sizes known at compile time
- automatically placed on function call stack when function starts
- automatically removed when function returns
- Dynamic memory
- compiler doesn’t know how much space is needed
- special call
new
can allocate space at runtime, placing it on the heap
- not automatically created nor destroyed
- can be advantageous
- can be annoying.
- need to explicitly free memory with matching
delete
- Dynamic memory errors
- leaks, forgetting to delete
- losing track of all references to dynamic memory
- orphaned memory, unreachable
- deleting the same allocation twice
- Two uses
- dynamic arrays
int* arr = new int[size]; delete [] arr
- dynamic objects
Point* p = new Point(3,2); delete p