2. C++ Memory Model Flashcards

Understand pointers, stack and heap memory.

1
Q

Every variable in C++ has these four things

A
  • name
  • type
  • value
  • memory location
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Which is larger, a memory location in the stack or the heap?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you create a new variable on heap memory?

A

Use the “new” keyword. e.g., int *i = new int;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

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?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Suppose we declare a variable as “int i;” How would you get the address of the memory location containing the contents of variable i?

A

&i

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How many memory allocations are made on the stack and on the heap for the following code?

int i = 0;
int *j = &i;

A

Two allocations on the stack and zero allocations on the heap.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How many memory allocations are made on the stack and on the heap for the following code?

int *i = new int;

A

One allocation on the stack and one allocation on the heap.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Let’s say p is a pointer to a class with a variable a.

What is expression p->a is equivalent to?

A

(*p).a

How well did you know this?
1
Not at all
2
3
4
5
Perfectly