CS 70

More Memory Diagrams

Before You Start

This activity will be done with your pair programming partner. Each pair should find one other pair to group up with (so you'll have a group of 4 people total).

While you're getting sorted out, ask each other what's an lvalue and an rvalue, and why do they have those strange names?

Activity

Draw memory diagrams for the following code snippets. Each pair should draw diagrams, and then once you're done, compare your diagrams with the other pair in your group.

Assume you don't have to model the internal behavior of the Coord constructor (which is synthesized by the compiler), just its effect on memory.

Snippet 1

#include "coord.hpp"
#include <iostream>

Coord makeOrigin() {
    return (0, 0);
}

int main() {
    Coord c = makeOrigin();

    // <---  draw memory diagram here

    std::cout << c << std::endl;
    return 0;
}

Snippet 2

#include "coord.hpp"
#include <iostream>

Coord& makeOrigin() {
    Coord c(0, 0);
    return c;           // This is bad!  Your memory diagram should show why.
}

int main() {
    Coord& c = makeOrigin();

    // <---  draw memory diagram here

    std::cout << c << std::endl;
    return 0;
}

Snippet 3

#include "coord.hpp"
#include <iostream>

Coord& makeOrigin(Coord& c) {
    c.x = 0;
    c.y = 0;
    return c;
}

int main() {
    Coord c1{5, 10};
    Coord& c2 = makeOrigin(c1);

    // <---  draw memory diagram here

    std::cout << c1 << std::endl;
    std::cout << c2 << std::endl;
    return 0;
}

(When logged in, completion status appears here.)