Tags: lec5

Q: When is stack memory released?  When is heap memory released?
A: stack: when a function returns, the corresponding stack frame is popped (so any local variables on it are released)
heap: when you explicitly call delete or delete[]

Q: new and delete (in C++) use underlying function calls that are typically used in C.  What are the underlying calls?
A: malloc and free

Q: What are some things that new does that malloc does not?
A: 1. new returns data of the correct type (malloc always returns a generic pointer that must be cast: void *).
2. new calls the constructor for you (if you have a class).

Q: When an array "decays" to a pointer (e.g., when you pass an array to a function expecting a pointer), what is some information that is lost?
A: With an array, sizeof tells you how many bytes are used in total by all the elements (knowing the element size, you could use this to compute the number of elements).
If you just have a pointer to the first element in an array, that pointer doesn't tell you how many elements there are in total.
Otherwise, an array and a pointer to the first element in an array can be used very similarly.

Q: If you want a pointer to the first element of an array of N MyStruct elements on the heap, how do you get it?
A: new MyStruct[N]

Q: If you want an array arr of N MyStruct elements on the stack, how do you get it?
A: MyStruct arr[N];
Note: support for a variable N is not universal in C++ (depends on standard and compiler) -- in some cases N will need to be a constant number.

Q: Which modification is NOT allowed, given the following usage of const?
const int* z = &x;
z = &y; // modify pointer
*z = 9; // modify value
A: Modifying the value (*z = 9) is not allowed.

Q: Which modification is NOT allowed, given the following usage of const?
int* const z = &x;
z = &y; // modify pointer
*z = 9; // modify value
A: Modifying the pointer (z = &y;) is not allowed.

Q: Internally, references are basically pointers, but there are 3 differences in terms of how we interact with them.  What are those differences?
A: 1. different syntax (for example, we use "." instead of "->")
2. a reference cannot point to nullptr
3. a reference is tied to the same value for ever (we can change the value, but not point to something different)

Q: If you want to replace the following pointer with a reference, how would the code change?
Coord* p = &coord;
f(*p);
A: Coord& r = coord;
f(r);