Week 10 Tutorial Sample Answers

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;
}

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.

    char *str = malloc (20 * sizeof (char));
    strcpy (str, "Hello");

Part 4: Memory leak

What is a memory leak?

What does dcc --leakcheck do?