Lecture 14: Dynamic Allocation and Midterm Review

Mar 4, 2024  β”‚  Last updated Mar 5, 2024 by Charlotte Curtis

HTML Slides html β”‚ PDF Slides PDF

Where we left off

  • Pointers and arrays
  • Pointers and structures
  • Pointers and functions
  • typedef
  • Preview of dynamic memory allocation

Textbook Sections 9.1, 9.2

Time t;
Time *pt = &t;

t.hour = 5;
t.minute = 0;
cout << pt->hour << ':' 
     << pt->minute << endl;

Today’s topics

Textbook Sections 9.2, 6.1

The heap and the stack

h:200 flavour

h:200 flavour

The new operator

To create a variable on the heap, use the new operator:

int x = 0; // x is a named memory location on the stack
int *ptr; // memory for pointer is on the stack
ptr = new int; // what it points at is on the heap

new structures

Every new needs a delete

Caution: this recycles the memory, but does not remove the pointer! Good idea to reset the pointer to NULL after a delete

Summary of new and delete

newdelete
Allocates memory on the heapReturns memory to the heap
Returns a pointer to the allocated memoryDoes not modify the pointer address

Risks:

Allocating variable sized arrays

Static vs dynamically allocated arrays

StaticDynamic
Size must be known at compile timeSize can be variable
Memory allocated on the stackMemory allocated on the heap
Memory freed automatically when variable goes out of scopeMust be manually deleted when you’re done with it
Limited by stack sizeLimited by system memory
Contiguous memoryContiguous memory

Midterm review exercise

Pub trivia style! Answers are now posted .

Q5:

int x = 5;
int *p1;
int *p2 = &x;

Q9:

int nums[8], n;
cin >> n;
for (int i = 0; i < n; i++) {
    cin >> nums[i];
}

Coming up next



Previous: Lecture 13: Pointers continued
Next: Lecture 16: Linked lists