Stack and heap

The two memory areas of an object program: the stack, with one frame per call, and the heap, where objects created by new live. References from one to the other, lifetime and overflow.

  • 25 cards
  • 4 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios

A few cards from the deck

  • Call stack: what is it?

    Show the answer

    The memory area where the frames of the running methods are stacked, the most recently called one on top.

    When main calls f which calls g, the stack holds main, f, g from bottom to top. When g returns, its frame is removed and f resumes.

  • What does this program print?

    ```java
    static void deplacer(Point p, int dx) {
    p.x += dx;
    }

    static void remettre(Point p) {
    p = new Point(0);
    }

    public static void main(String[] args) {
    Point pt = new Point(1);
    deplacer(pt, 2);
    remettre(pt);
    System.out.println(pt.x);
    }
    `

    • 3
    • 1
    • 0
    • 2
    Show the answer

    3

    deplacer receives a copy of the reference: p.x += dx modifies the heap object, which pt sees too, so x is 3. In remettre, p = new Point(0) only changes the frame's local variable, which disappears on return: pt still refers to the old object.

  • Each method call pushes a … that holds the parameters and local variables; it is popped when the method ….

    Show the answer

    Each method call pushes a frame that holds the parameters and local variables; it is popped when the method returns.

    Pushing and popping follow the order of calls: the last one called is the first to finish. This is what makes recursion possible.

  • Stack frame: what is it?

    Show the answer

    The area of the stack belonging to one method call, which holds its parameters and local variables.

    Each call has its own frame, even for a method calling itself: the local variables of two recursive calls are distinct. The frame disappears on return, and its variables with it.

  • A program stops with java.lang.StackOverflowError, the trace showing the same factorial method hundreds of times. What is the cause?

    • Recursive calls that never end, for lack of a base case
    • The heap is full: too many objects were created
    • A local variable went past the maximum value of an int
    • The garbage collector did not free the stack frames
    Show the answer

    Recursive calls that never end, for lack of a base case

    The repeated trace shows frames piling up. Frames do not depend on the garbage collector (they are removed on return), and a full heap gives another error, OutOfMemoryError.