CSCI0200
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- tags: resources, spr22 --- # How to Develop a Memory Diagram A *memory diagram* shows the contents of two areas of memory that a programming environment maintains as part of running code. - the *heap* stores objects (or other structured data) in memory locations/addresses - the *environment* associates each variable name with a heap location or basic datum (e.g., int, bool) Working with memory diagrams can help us understand how a program is---or should be---running. They should also help you develop good conceptual models about how language constructs work. We create memory diagrams at two different levels of detail, depending on context. The first level uses hand-drawn arrows to show references between objects. The second level uses addresses to represent which object a field or name refers to. ### Sample Memory Diagram Consider this sample of code: ```=java class CSCourse { private int number; private Faculty taughtBy; } class Faculty { private String name; } Faculty rob = new Faculty("Rob"); CSCourse math = new CSCourse(220, rob); CSCourse data = new CSCourse(111, new Faculty("Milda")); CSCourse us = new CSCourse(200, data.getTaughtBy()); ``` Here is the diagram with arrows (not addresses): ![](https://i.imgur.com/hD39cKr.png) <!-- ![](https://i.imgur.com/sYXT9ZW.jpg) --> Here is the diagram with addresses (not arrows): ``` Environment Heap rob -> loc1010 loc1010 -> Faculty("rob") math -> loc1011 loc1011 -> CSCourse(220, loc1010) data -> loc1013 loc1012 -> Faculty("Milda") us -> loc1014 loc1013 -> CSCourse(111, loc1012) loc1014 -> CSCourse(200, loc1012) ``` #### Breaking Down The Memory Diagram Now, let's break down the code line by line and see what the memory looks like at each stage. 1. ```Faculty rob = new Faculty("Rob");``` This code creates a variable within the environment called 'rob' which points to a new faculty object stored in the heap: ![](https://i.imgur.com/JEpnpqh.png) 2. `CSCourse math = new CSCourse(220, rob);` This line creates a new variable in the environment called 'math' which points at a new CSCourse object located within the heap. This new CSCourse object points to the faculty object for its taughtby attribute: ![](https://i.imgur.com/apq1bvu.png) 3. `CSCourse data = new CSCourse(111, new Faculty("Milda"));` This line starts by creating a new Faculty object that isn't pointed to by any variable. This object is stored within the new CSCourse's taughtby attribute. This CSCourse can be accessed through the 'data' variable. ![](https://i.imgur.com/miQupw4.png) 4. `CSCourse us = new CSCourse(200, data.getTaughtBy());` Now another new CSCourse object is created (accessible through the 'us' variable). This new course has 200 as its number attribute and points to the same heap object as data's taughtby attribute. ![](https://i.imgur.com/WJKz9hx.png) ### Creating a Memory Diagram from Code We create memory diagrams by manually tracing the steps of the code, in order, and taking the following steps: - Whenever your code **creates an object** (with `new`), put the object in the heap (at the next unused heap location) - If the object is an `ArrayList`, set aside 8 locations for its elements (even if some are unused) - Whenever your code **introduces a new name**, such as a local variable, constant, or method parameter, put the name in the environment. Associate the name with the heap location of the object (or the basic value) that the name refers to. - Whenever your code **calls a method or function**, box off a local segment of the environment. Parameters and local variables go into this local segment. When the method/function call finishes, delete the local segment from the environment (the heap is not affected) - Whenever your code **assigns a new value to a field**, change the field contents in the *heap*. - Whenever your code **assigns a new value to a name**, change the *environment* to associate the name with the heap location or basic data of its new value - Whenever your code **uses a variable name or field name** start from the environment and follow the references until you get to a basic value or location address. That value/address is the result of that expression. ### FAQ - **Do objects ever leave the heap?** Language implementations use a process called *garbage collection* to remove objects from the heap when they are no longer being used. When you draw memory diagrams, ignore garbage collection and assume objects live in the heap forever. We will do a lecture on garbage collection towards the end of the course. - **Do names ever leave the environment?** Names that are introduced by methods (parameters, local variables) leave the environment when the method call has finished. - **Do the location numbers mean anything?** Yes. The order of the location numbers indicates the order in which objects were created while running your program (this can change with garbage collection, but we'll ignore this for now). The gaps between location numbers also correspond to the size of the object, in terms of the number of fields (or reserved slots in the case of `ArrayList`). - **Can we ever run out of location numbers?** Technically yes, because a computer has only a limited amount of memory (and only some of that memory can be used for the heap for any one program). We're not going to ask you to trace anything large enough for this to be an issue. --- *Please let us know if you find any mistakes, inconsistencies, or confusing language in this or any other CS200 document by filling out the [anonymous feedback form](https://forms.gle/JipS5Y32eRUdZcSZ6)!* *(you do have to sign in but we don't see it)*

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully