Week 10 Tutorial Questions

Reminder: Assignment 2 released

If you have any questions about Assignment 2, feel free to ask them now.

Part 1: Malloc and free

In this section we'll visit malloc and free.

Group activity

Using your knowledge of malloc() and sizeof(), write up code to malloc the following:

struct my_struct {
    int number;
    char letter;
    double another_number;
}

Before the activity:
  1. Ask How much memory is needed for an int vs a double and char -> introduce sizeof() here.
  2. Ask Students what malloc does, what arguments it takes and what it returns
    • Malloc allocates a block of memory on the heap.
    • Arguments: The amount of memory that we are asking for.
    • Return: A pointer containing the memory address of where that memory is.
  3. Ask Students what free does, why we use it and when we use it.
    • De-allocate space allocated by malloc
    • Used to clean up any malloc'd memory at the end of the program or when we are done working with a piece of memory
Note, you can use the hotel analogy for explaining the relationship between malloc and free.

The activity:

After the activity:

Discuss some of the differences between creating variables with or without malloc, and where we'd prefer to use one over the other.

Potential talking points:

Part 2: Diagramming Linked Lists (10 mins)

In this activity we will run through the following instructions and build a diagram.

malloc memory for a new node called node1

node1 data = 3
node1 next = NULL

make the head pointer points to node1

malloc memory for a new node called node2

node2 data = 9
node2 next = NULL

add node2 to the tail of the list, making node1 next point to node2

malloc memory for a new node called node3

node3 data = 5
node3 next = NULL

add node3 to the head of the list, making node3 next point to the current head of the list
make the head point to node3

Part 3: Malloc and Strings

Give an example of allocating memory for a string of size 20 and then store "Hello" in that.

Part 4: Memory leak

What is a memory leak?

What does dcc --leakcheck do?

A memory leak is when a program doesn't free memory allocated with malloc.

This is (generally) not important in the programs we write in COMP1511 because they run only for short periods of time and allocate small amounts of memory.

But if, for example, a web browser allocates memory (calls malloc) every time a user visits a page but doesn't free the memory (call free) when they leave the page, the web browser's memory use will steadily grow, eventually causing performance problems and then if it exhausts available memory, termination.

So we want you to practice free-ing memory in lab exercises.

dcc --leakcheck warns you when you haven't freed your memory. It uses an underlying tool named valgrind. It translates valgrind output into something hopefully a COMP1511 student can understand.

Note, the operating system reclaims all memory when a program exits.