2. C++ Memory Model Flashcards
Understand pointers, stack and heap memory.
Every variable in C++ has these four things
- name
- type
- value
- memory location
Which is larger, a memory location in the stack or the heap?
The stack.
Memory on the stack starts at the top and goes down, while memory on the heap starts at the bottom and goes up.
How do you create a new variable on heap memory?
Use the “new” keyword. e.g., int *i = new int;
What happens if a function returns a pointer to a local variable and then we try to assign something to the memory location the pointer is pointing to?
Unknown. Depending on the compiler settings, the compiler may report that the local variable address is being returned, which could be treated as a warning or as a compilation error; Or, if the program is allowed to compile then at runtime the program may terminate due to a memory fault.
Suppose we declare a variable as “int i;” How would you get the address of the memory location containing the contents of variable i?
&i
How many memory allocations are made on the stack and on the heap for the following code?
int i = 0;
int *j = &i;
Two allocations on the stack and zero allocations on the heap.
How many memory allocations are made on the stack and on the heap for the following code?
int *i = new int;
One allocation on the stack and one allocation on the heap.
Let’s say p is a pointer to a class with a variable a.
What is expression p->a is equivalent to?
(*p).a