Lab 3: Pointers, malloc, and Memory model

Overview

Previously we saw how pointers can be used to store the address of some other location in memory, and how we can:

  1. Use * to declare a type to be a pointer

  2. Use * as the dereference operator to go to the memory address stored in the pointer

  3. Use the & address operator

As we compile and run a program and use pointers, where in memory does it point to? What is the difference between statically defined variables, memory on the stack used to keep track of function calls and their parameters, and memory on the heap for dynamically allocated memory using malloc? This week we explore these ideas.

Reading

While there are multiple items listed for this week's reading, each one is only a few pages for a total of about 14 pages.

  1. From the "C Pointers Tutorial by Ted Jensen" document (available in Piazza Resources tab):

    • Ch. 5: Pointers and Structures, pp. 22-24

    • Ch. 7: More on Multi-Dimensional Arrays, pp. 30-31

    • Ch. 9: Pointers and Dynamic Allocation of Memory, pp. 34-36

  2. Memory model of the Heap and the Stack: https://icarus.cs.weber.edu/~dab/cs1410/textbook/4.Pointers/memory.html
    You can read it, and/or stream a 4 minute video version.

  3. Pointers, Stack & Heap Memory, malloc() (4 pages)
    https://people.cs.clemson.edu/~jmarty/courses/commonCourseContent/Module2-ProgrammingReview/MemoryAndMalloc.pdf

Hint: To find useful bibliographic entries of your own, do a google search within the .edu domain, such as: malloc tutorial site:*.edu

Lab Questions

Your tutorial should answer the questions shown below. I suggest you keep them in mind as you do your reading and write your 260 word outline. Note that the code and diagrams described below must be your own unique creations. Each section should include explanations of what the code does.

  1. Write your own program that includes:

    • static variables

    • Calling a function with parameters that in turn calls a second function

    • Dynamically allocated memory using malloc

  2. For the above program, create and provide a memory model diagram showing where each variable, function, parameter, and dynamically allocated section of memory is located (static, stack, heap). You can draw this using Google slides drawing tools, or you can draw it on a piece of paper, take a picture of it, and include that picture.

  3. Show how memory dynamically allocated using malloc can then be referenced using standard square bracket 2-d array notation (e.g. theArray[ row][ col] ).

  4. Consider the program shown below and its output when run online at cpp.sh. Create and use a memory model diagram to explain why the output is unexpected and what causes that.