CPSC 221

Linked Memory

Today

Announcements

  • PA1 is out, due Monday Oct 5
  • Examlet 1 is this week — Thursday through Sunday. Book your seat on PrairieTest
  • HW1 closed Monday


Lesson 3.2 (video)

  • Linked memory
  • Singly linked lists
    • insertAtFront
    • printReverse

Something NEW!!

Make at least 3 observations about this code:

template <class LIT>
struct Node{
   LIT data;
   Node * next;
   Node(LIT nData, Node * next=nullptr): data(nData) {}
};
  •  
  •  
  •  
  •  

A metaphor for memory…

Variables and Pointers:

Backtrack to variables:




Special variable type:

loc name val type

Pointers and dynamic memory:

int * p;
loc name val type
loc name val type

Fun and games with pointers: (warm-up)

int * p, q;

What type is q? ______________


int *p;
int x;
p = &x;
*p = 6;
cout << x;
cout << p;

cout << x;   What is output? ______________

cout << p;   What is output? ______________

Write a statement whose output is the value of x, using variable p: ______________

int *p, *q;
p = new int;
q = p;
*q = 8;
cout << *p;
q = new int;
*q = 9;
p = nullptr;
delete q;
q = nullptr;



cout << *p;   What is output? __________



p = nullptr;   Do you like this? __________

q = nullptr;   Do you like this? __________

Memory leak:


Deleting a null pointer:

Dereferencing a null pointer:

Let’s explore…

1 pointers1.cpp one int, two names
2 pointers2.cpp new, delete, and aliasing
3 pointers3.cpp a leak, and two ways to meet nullptr


g++ -o p1 pointers1.cpp && ./p1