csperkins.org

Advanced Systems Programming H/M (2025-2026)

Lecture 4: Resource Ownership and Memory Management

This lecture begins to discuss the various options available for resource ownership and memory management in modern programming languages. It discusses how running programs are arranged in memory, and outlines the need for automatic memory management. It then discusses two approaches to memory management: reference counting and region-based memory management, considering their various costs and benefits. The region-based approach used in Rust is shown to have several important benefits, in terms of efficient and deterministic memory management, but at the cost of making certain classes of program more complex to express.

Part 1: Memory

The first part of this lecture reviews of a process is stored in memory, and what different types of memory exist within a running process, as a prelude to the discussion of automatic memory management. It also discusses how memory-unsafe behaviour can lead to security vulnerabilities through buffer overflows attacks.

 

00:00:00.200 In this week’s lecture, I want to

00:00:02.200 talk about resource ownership and memory management.

 

00:00:06.000 In this first part, I’ll talk about

00:00:07.866 how a process is stored in memory,

00:00:10.100 and what memory has to be managed.

 

00:00:12.400 Then, in the following parts,

00:00:14.300 I’ll start our discussion of different

00:00:16.166 approaches to memory management,

00:00:18.166 starting with reference counting and region-based

00:00:20.766 memory management, and how these interact with

00:00:23.366 resource management.

 

00:00:26.600 Let’s start by talking about memory.

 

00:00:30.600 To understand memory management, you must first

00:00:33.400 understand what memory needs to be managed.

00:00:35.800 In all modern operating systems, every process

00:00:38.300 is given a virtual address space in

00:00:40.700 which it executes. Each process thinks it’s

00:00:43.066 the only one running on the machine,

00:00:45.466 and has access to the full range

00:00:47.033 of memory addresses.

 

00:00:49.000 The underlying hardware translates these virtual addresses

00:00:52.000 into physical addresses that represent particular locations

00:00:55.000 in real memory, and makes sure that

00:00:57.966 the different processes are isolated from each other.

 

00:01:01.300 The virtual address space that a process

00:01:03.566 sees is divided into several different parts.

 

00:01:06.933 At the bottom of memory, starting with

00:01:09.000 the lowest numbered address sits the program

00:01:11.033 text itself: the machine code that represents

00:01:14.466 the running program. That’s immediately followed by

00:01:17.800 the static data and space for any

00:01:19.900 global variables.

 

00:01:22.000 Following this in memory is the heap:

00:01:24.100 memory allocated using malloc(), or similar mechanisms.

 

00:01:27.900 Following that is the memory used to

00:01:30.200 hold shared libraries and memory mapped files.

 

00:01:33.000 Then the stack space, growing down from

00:01:35.100 the top of user accessible memory.

 

00:01:37.533 Then, finally, the operating system kernel itself

00:01:40.566 occupies the top part of the address space.

 

00:01:43.433 How much memory is allocated to each

00:01:45.600 of these, and what virtual addresses each

00:01:47.900 sits between, depend on whether you have

00:01:50.900 a 32-bit or a 64-bit machine,

00:01:53.433 and on what operating system you’re running.

 

00:01:55.900 But all the systems follow the same basic approach.

 

00:02:01.566 The program text, data, and global variables

00:02:04.966 occupy the lowest part of the address space.

 

00:02:08.100 There are four parts to this.

 

00:02:10.966 The very lowest page of memory,

00:02:12.800 usually the first 4096 bytes starting at

00:02:16.133 address zero, is reserved. In languages like

00:02:20.166 C, a null pointer is represented by

00:02:22.400 address zero, so the hardware virtual memory

00:02:25.000 controller is programmed to prohibit access to

00:02:27.766 that address, and to adjacent addresses,

00:02:30.366 as a way of trapping null-pointer dereferences.

 

00:02:33.800 Trying to access this memory will trap

00:02:36.133 into the operating system, which will kill

00:02:38.100 the process with a segmentation violation error.

 

00:02:42.000 Following this reserved page, sits the compiled

00:02:44.700 program text. That is, the machine code

00:02:47.966 representing the program. This occupies the lowest

00:02:51.266 part of the address space, starting just above address zero.

 

00:02:55.800 Next comes the data segment.

 

00:02:58.233 This comprises string literals and static global variables.

00:03:02.266 Data and global variables where the value

00:03:04.233 is known at compile time.

 

00:03:06.500 These are stored in the compiled binary,

00:03:08.866 along with the executable machine code,

00:03:11.266 and loaded into memory following the program text.

 

00:03:15.000 Then, space is allocated for the BSS segment.

00:03:18.966 This provides reserved space for uninitialised

00:03:21.933 global variables defined in the program.

 

00:03:24.600 The name BSS stands for “block started

00:03:27.400 by symbol”, and is a historical relic.

 

00:03:30.833 The program text and data segments are

00:03:33.333 fixed. They comprise the compiled program code

00:03:36.033 and data known at compile time.

 

00:03:38.666 Similarly, the size of the BSS segment

00:03:41.133 is known at compile time.

 

00:03:43.500 In older operating systems,

00:03:45.533 the program and data always start at a fixed

00:03:48.000 location at the start of the memory.

 

00:03:50.500 In modern systems,

00:03:52.033 they’re still loaded near the start of the memory,

00:03:54.766 but the actual starting address is randomised

00:03:56.833 each time the program runs.

 

00:03:59.000 Why is it randomised?

 

00:04:01.066 It’s a security measure.

 

00:04:02.800 It makes it harder for code executed as part of

00:04:05.366 a buffer overflow attack to call into

00:04:07.800 other parts of the program, since it

00:04:09.966 can’t know where they’ll be located in memory.

 

00:04:14.633 As a program executes, it needs space

00:04:17.333 to hold the function parameters, return addresses,

00:04:19.800 and local variables.

00:04:21.833 These are stored on the stack.

 

00:04:24.900 The stack occupies the top of user

00:04:27.000 accessible memory, starting at a random address

00:04:30.000 for security, and grows downwards.

 

00:04:33.566 Each time a function is called,

00:04:35.366 starting with main(), the parameters to that

00:04:38.133 function, the return address, and a pointer

00:04:40.766 to the previous stack frame are pushed

00:04:42.566 onto the stack. They occupy the next

00:04:45.466 addresses below the previous top of the stack.

 

00:04:48.866 And when the function starts to execute,

00:04:51.200 space for its local variables is similarly

00:04:53.433 allocated on the stack.

 

00:04:56.033 If that function calls other functions,

00:04:58.166 the stack grows, as the new stack frames are created.

 

00:05:02.000 And when a function returns, the stack

00:05:04.500 shrinks and the memory it used on

00:05:06.233 the stack is automatically reclaimed.

 

00:05:08.866 The compiler generates the code to manage

00:05:11.333 the stack, as part of the code

00:05:13.133 it generates for each function.

 

00:05:15.333 It knows how the return address, parameters, and stack

00:05:18.500 pointer are represented, and how to grow

00:05:21.000 and shrink the stack.

 

00:05:23.000 And the operating system generates the stack

00:05:25.033 frame for main() when the program starts,

00:05:27.900 with a return address pointing to the process cleanup code.

 

00:05:32.000 To the programmer, the stack is managed automatically.

 

00:05:35.600 Ownership of the stack memory follows function invocation.

 

00:05:41.500 This slide shows an example of a simple C program.

 

00:05:45.100 It comprises a main() function that inspects

00:05:47.566 the values given as command line arguments,

00:05:49.966 and either prints a greeting or a usage message.

 

00:05:53.833 When this program starts to execute,

00:05:56.366 and main() is called, the stack contents

00:05:59.000 are as shown in the green region

00:06:01.033 on the right of the slide.

 

00:06:03.466 The stack contains the arguments to main(),

00:06:06.300 argc and argv, the address to return

00:06:10.066 to once main() completes, and the local variables for main.

 

00:06:14.833 When execution reaches the printf() line,

00:06:17.966 shown in red, and the function is

00:06:20.233 called, a new stack frame is created.

 

00:06:24.266 This new stack frame holds the arguments

00:06:26.533 for printf(), the address to return to

00:06:29.466 once the printf() call finishes, and a

00:06:31.733 pointer to the previous stack frame.

 

00:06:34.633 The address of the previous stack frame

00:06:36.533 is stored for ease of debugging,

00:06:38.266 so stack traces can be printed and

00:06:40.500 so debuggers can trace program execution.

 

00:06:44.200 As printf() starts to execute, space is

00:06:46.733 allocated on the stack for any local variables it uses.

 

00:06:50.566 And, if printf() itself calls any functions,

00:06:53.266 the stack will continue to grow as needed.

 

00:06:57.333 This suggests the classic buffer overflow attack.

 

00:07:01.333 If the language is not type safe,

00:07:03.566 and doesn’t check array bounds,

00:07:05.600 then the call to printf() can be arranged

00:07:07.700 so that it writes past the bounds of a local

00:07:09.600 variable stored on the stack.

 

00:07:12.000 When this happens, it overwrites whatever is

00:07:14.633 stored in the next higher addresses on the stack.

 

00:07:18.366 What would that be?

 

00:07:20.166 Well, maybe some other local variables,

00:07:23.200 but also the pointer to the previous stack frame,

00:07:26.000 then the return address of the function.

 

00:07:29.000 The goal is to overwrite the return address,

00:07:31.700 and some of the following memory.

00:07:33.933 The attacker tries to fill the memory

00:07:36.066 following the return address with the code

00:07:37.866 they want to execute. And to overwrite

00:07:40.500 the return address so that it points to that code.

 

00:07:44.266 When the function then returns, rather than

00:07:47.233 return to the correct place, it returns

00:07:49.733 instead to the return address written during

00:07:51.766 the overflows and executes the attacker’s code.

 

00:07:55.533 It’s a technique known as stack smashing.

 

00:07:59.033 The link to the Phrack article on

00:08:01.233 the slide is the classic explanation of this technique.

 

00:08:05.766 Modern systems have workarounds, of course.

 

00:08:09.900 They randomise the location of the stack

00:08:11.833 each time a program runs, to make

00:08:13.833 it harder to known what value to

00:08:15.300 overwrite the return address with.

 

00:08:18.000 And they arrange for the virtual memory hardware to mark

00:08:20.566 the stack memory as non-executable,

00:08:22.800 so the system will refuse to execute the code

00:08:25.466 if the return address is successfully overwritten.

 

00:08:29.000 These techniques help.

00:08:30.933 The classic stack smashing attack I’ve described

00:08:34.000 won’t work on a modern system.

 

00:08:36.933 But they don’t entirely solve the problem.

00:08:39.666 Newer attacks, such as return oriented programming,

00:08:43.100 can defeat the protections in some cases.

 

00:08:46.000 The real solution, of course, is to

00:08:48.533 use a language that checks array bounds,

00:08:51.333 and prevents buffer overflows in the first place.

 

00:08:56.000 Back to memory management.

 

00:08:58.400 In addition to the program code and the stack,

00:09:01.333 the heap holds explicitly allocated memory.

 

00:09:06.733 This is memory allocated by calls to

00:09:08.666 functions such as malloc() and calloc() in C;

00:09:11.966 boxed memory in Rust;

00:09:13.800 and objects allocated using new() in Java.

 

00:09:17.500 The heap starts at a low address in memory,

00:09:20.500 following the BSS segment,

00:09:22.266 and grows upwards towards the stack.

 

00:09:25.100 As you might expect by now,

00:09:26.733 the exact starting address for heap allocations

00:09:28.933 is randomised for security.

 

00:09:31.733 In general, successive heap allocations will occupy

00:09:34.733 consecutive blocks in memory,

00:09:36.633 although multi-threaded systems will partition the heap

00:09:39.800 so that each thread that its own

00:09:41.433 space in which to make allocations,

00:09:43.300 without needed to coordinate with other threads.

 

00:09:46.433 And, depending on the processor, small allocations

00:09:49.900 may be rounded up in size to

00:09:51.533 align on a 32 bit or a 64 bit boundary.

 

00:09:56.500 While the stack is managed automatically as

00:09:58.800 functions are called, the challenge of memory

00:10:01.233 management is primarily about how to manage

00:10:03.333 and reclaim the heap memory.

 

00:10:06.000 This can be done manually, by calling the free() function.

 

00:10:10.000 It can be done automatically via reference

00:10:12.533 counting or garbage collection, as we’ll discuss

00:10:15.200 in the next lecture.

 

00:10:17.000 Or it can be done automatically,

00:10:18.966 based on regions and lifetime analysis,

00:10:21.233 as I’ll discuss in later part of this lecture.

 

00:10:26.000 In addition to allocating heap memory,

00:10:28.733 most operating systems allow memory mapped files,

00:10:31.900 allowing data on disk to be directly

00:10:34.100 mapped into the address space.

 

00:10:37.000 On Unix-like systems, such mappings are created

00:10:39.866 using the mmap() system call.

 

00:10:43.000 The mmap() call returns a pointer to

00:10:45.133 a block of memory that acts as

00:10:46.633 a proxy for the file. Reading from

00:10:49.800 that memory will page into the relevant

00:10:51.533 part of the file into memory, and return its contents.

 

00:10:54.933 And writes to that block of memory will eventually be

00:10:57.400 paged back out to disk by the operating system.

 

00:11:01.266 The file is paged in and out

00:11:03.066 of memory as needed, with only the

00:11:05.333 parts of the file being accessed being

00:11:07.200 loaded. It’s an effective way of providing

00:11:10.066 random access to parts of a file.

 

00:11:13.433 Such memory mapped files generally occupy the

00:11:16.200 space between the heap and the stack.

 

00:11:19.000 Shared libraries are usually implemented using memory

00:11:21.666 mapped files, and are mapped into this memory space too.

 

00:11:27.333 Finally, the operating system kernel resides at

00:11:30.033 the top of the address space.

 

00:11:32.566 Kernel memory isn’t directly accessible to user

00:11:34.900 programs, and attempts to access that memory

00:11:37.566 will result in a segmentation violation.

 

00:11:41.000 The hardware provides a special machine code

00:11:43.100 instruction, known as syscall on 64-bit Intel

00:11:46.733 processors, that switches the system to kernel

00:11:49.700 mode and executes a particular function in

00:11:52.100 kernel memory, after performing some permission checks.

 

00:11:56.000 The kernel itself can read and write

00:11:58.566 to the entire address space. The hardware

00:12:01.166 protects the operating system kernel from the

00:12:03.200 user processes, but the operating system has

00:12:05.600 to be able to control those processes

 

00:12:09.600 That concludes our discussion of how

00:12:11.533 programs are stored in memory.

 

00:12:13.700 In the next part, I’ll start to

00:12:15.333 talk about memory management, and the use

00:12:17.666 of reference counting as a memory management technique.

  1. Many But Finite, Anatomy of a Program in Memory, blog post, January 2009.
  2. Aleph One, Smashing the Stack for Fun and Profit, Phrack 49, November 1996.

Part 2: Automatic Memory Management: Reference Counting

This part of the lecture begins to discuss automatic memory management. It outlines how reference counting works, and discusses its benefits in terms of simplicity and predictability, along with its overheads and limitations.

 

00:00:00.400 In this part, I’ll talk about the goals

00:00:02.633 of automatic memory management.

00:00:04.566 And I’ll discuss one of the simplest automatic memory

00:00:06.866 management schemes, reference counting.

 

00:00:11.000 Automatic memory management

00:00:12.900 is frequently distrusted by systems programmers.

00:00:15.633 There’s a general belief that it has high overheads.

00:00:19.166 That it’s slow, CPU hungry, and wastes memory.

00:00:22.900 And that the use of automatic memory management

00:00:25.466 introduces unpredictability into the timing

00:00:28.200 of time sensitive operations.

 

00:00:31.000 And to some extent this belief is true.

 

00:00:34.066 There are many different types of automatic

00:00:36.100 memory management. And some of them do

00:00:38.600 have high CPU costs. Some of them

00:00:41.000 do waste memory. And some do introduce

00:00:43.866 unpredictability into timing.

 

00:00:46.733 Equally, though, there are very real problems

00:00:49.266 due to manual memory management.

 

00:00:52.000 Managing memory manually has unpredictable overheads.

 

00:00:56.066 As a programmer you known when you

00:00:58.266 call malloc() and free(), but you have

00:01:00.466 no idea how long those calls will

00:01:01.933 take to execute. And they can be

00:01:04.166 quite processor intensive, and can take unpredictable

00:01:06.666 amounts of time, in some cases.

 

00:01:10.000 And there are the numerous, and well

00:01:11.966 known, problems due to memory leaks,

00:01:13.900 memory corruption, buffer overflows, use-after-free bugs,

00:01:16.933 and iterator invalidation, all of which are

00:01:19.833 due to manual memory management.

 

00:01:23.000 Systems programmers have focussed on the problems

00:01:25.333 of moving to automatic memory management,

00:01:27.466 discounting the problems of the status quo.

 

00:01:31.166 Furthermore, we’re starting to see automatic memory

00:01:33.966 management techniques that solve some of the

00:01:35.800 problems with older approaches. New garbage collection

00:01:39.566 algorithms have lower overheads and are more

00:01:41.466 predictable. And systems have gotten faster,

00:01:44.633 making the overheads of existing algorithms more acceptable.

 

00:01:48.300 And different approaches, such as region-based memory

00:01:51.133 management, are starting to see widespread use,

00:01:54.766 and offer more predictability and stronger compile-time

00:01:58.266 behaviour guarantees.

 

00:02:00.700 For many systems programs, it may be

00:02:02.900 time to reconsider the cost-benefit tradeoff for

00:02:05.266 automatic memory management, to see if the

00:02:07.866 balance has shifted.

 

00:02:11.500 Systems programs traditionally used a mix of

00:02:13.900 manual and automatic memory management.

 

00:02:17.600 The memory used for the stack is managed automatically.

 

00:02:21.666 In the sample code on the slide,

00:02:23.600 for example, the memory for the local

00:02:25.833 variable, di, in the saveDataForKey() function is

00:02:29.266 automatically allocated when the function is called,

00:02:32.900 and automatically freed when the function returns.

 

00:02:37.000 This is so common that we don’t even think about it.

 

00:02:40.166 Stack-based memory management, in this form,

00:02:43.466 works extremely well for languages like C

00:02:46.366 and C++ that support complex value types.

 

00:02:49.400 That is, for languages that can put

00:02:51.666 structs on the stack and pass them by value.

 

00:02:55.800 It works less well for languages like

00:02:57.600 Java, where objects are heap allocated.

 

00:03:00.666 In Java, the variable, di, would be

00:03:03.166 a reference to a heap allocated object,

00:03:05.400 which would need to be garbage collected.

 

00:03:07.833 Only the reference to that object would

00:03:10.066 be stored on the stack. While,

00:03:12.600 in C and C++, the entire object

00:03:14.966 can be efficiently managed on the stack.

 

00:03:17.566 The stack in C and C++ is

00:03:20.000 an example of successful automatic memory management.

 

00:03:24.000 The heap, on the other hand,

00:03:25.900 is generally managed manually. Allocation is by

00:03:28.866 a call to malloc(). Deallocation, if the

00:03:31.266 programmer remembers to do so, is by

00:03:33.833 an explicit call to free().

 

00:03:37.900 It would be good to have an

00:03:39.266 effective and automatic way of managing the

00:03:41.033 heap. Something that’s as simple, efficient,

00:03:44.300 and effective as managing the stack.

 

00:03:47.266 The goal of automatic memory management is

00:03:49.366 to manage the heap. To find memory

00:03:51.966 that’s no longer in use, and make

00:03:53.900 that space available for reuse. To look

00:03:56.033 for objects that are no longer referenced

00:03:58.166 by the running program, and to free their memory.

 

00:04:01.000 And to do so efficiently and automatically.

 

00:04:05.000 And to do so safely.

 

00:04:06.966 It’s better to waste memory, and to keep an

00:04:09.033 object alive when it shouldn’t be,

00:04:11.200 than to deallocate the memory used by

00:04:13.766 an object that’s potentially still in use.

 

00:04:16.500 There are three approaches to automatically

00:04:18.800 managing the heap.

 

00:04:21.000 The first is reference counting, that I’ll

00:04:22.933 discuss in a minute.

 

00:04:25.000 The second is region-based lifetime tracking,

00:04:27.700 that I’ll discuss in the next part of this lecture.

 

00:04:31.000 And the third is to use garbage

 

00:04:32.933 collection, that I’ll discuss in lecture 6.

 

00:04:37.500 The first of the automatic memory management

00:04:40.100 techniques is reference counting.

 

00:04:43.500 Reference counting is simple and easy to understand.

 

00:04:47.166 When allocating memory for an object,

00:04:49.433 the allocation contains additional space for a

00:04:51.500 reference count that’s stored along with the object.

 

00:04:54.900 That is, every object has a hidden

00:04:57.566 extra field, large enough to hold an

00:04:59.866 integer value, that’s stored alongside the object

00:05:03.100 and managed by the runtime system,

00:05:04.966 invisibly to the programmer.

 

00:05:07.333 This extra field contains a reference count.

00:05:10.400 It counts how many other objects have

00:05:12.833 a pointer, a reference, to this object.

 

00:05:15.333 When a heap allocated object is created,

00:05:18.033 the reference count is set to one,

00:05:20.133 and a reference to the object is returned.

 

00:05:22.866 When a new reference, a new pointer,

00:05:25.366 to the object is made, then the

00:05:28.066 reference count is increased by one.

 

00:05:30.233 When a reference is removed or changed,

00:05:32.766 so that it no longer points to

00:05:34.866 the object, then the reference count is decreased by one.

 

00:05:38.300 If the reference count reaches zero,

00:05:40.866 then there are no references left that

00:05:43.466 point to the object, and it may

00:05:44.966 be reclaimed, and it’s memory deallocated.

 

00:05:48.000 If an object that contains references to

00:05:50.300 other objects is reclaimed, this removes a

00:05:52.966 reference to those objects. Doing so potentially

00:05:56.233 causes their reference counts to go to

00:05:58.433 zero, triggering further reclamation.

 

00:06:01.066 The reference counts are maintained automatically.

00:06:04.100 In a compiled language with reference counting,

00:06:07.133 such as the Objective C runtime used

00:06:09.766 in iPhones, then the compiler generates the

00:06:12.500 code to manage references and reclaim objects

00:06:14.966 when pointers are manipulated. In an interpreted

00:06:18.533 language with reference counting, such as Python

00:06:21.400 or Ruby, the interpreter updates the references

00:06:24.533 and reclaims the objects.

 

00:06:28.500 The key benefit of reference counting is

00:06:31.066 that it’s predictable and understandable.

 

00:06:34.000 It’s easy to explain how reference counting works.

 

00:06:37.533 It’s easy to understand when memory is

00:06:39.866 reclaimed, and what actions in a program

00:06:42.333 might trigger memory to be reclaimed.

 

00:06:45.000 It’s easy to understand what is the

00:06:46.766 overhead and what is the cost.

00:06:49.233 It’s one additional integer per object;

00:06:51.166 an increment of a reference count when

00:06:53.466 taking a pointer to an object;

00:06:55.200 and a decrement of a reference count,

00:06:57.033 an if statement, and a potential call

00:06:58.900 to free() when removing a reference.

 

00:07:01.933 The behaviour is intuitive to programmers –

00:07:04.233 and that counts for a lot.

 

00:07:06.466 Reference counting is also incremental.

 

00:07:09.266 Memory is reclaimed in small bursts, and the costs

00:07:12.133 that occur are an occasional small overhead

00:07:14.666 on pointer operations. There are few long

00:07:17.233 bursts of memory management activity, and it’s

00:07:19.800 clear what might trigger such bursts.

 

00:07:24.000 Reference counting also has some costs.

 

00:07:27.600 Cyclic data structures can be produced that

00:07:30.100 contain mutual references. That is, a set

00:07:33.100 of objects can reference each other in

00:07:35.233 a loop, such that the objects are

00:07:37.666 all reachable from some other object,

00:07:39.166 so the reference count never reaches zero,

00:07:41.733 but not from the rest of the program.

 

00:07:44.566 This can lead to a disconnected set

00:07:46.466 of objects, unreachable from the rest of

00:07:48.400 the code, that aren’t reclaimed because they

00:07:50.833 have non-zero reference counts.

 

00:07:53.000 That is, it can leak memory.

 

00:07:56.400 The programmer needs to notice, and explicitly

00:07:59.066 set one of the references to null,

00:08:00.933 to break the cycle before removing the

00:08:03.066 last other pointer to the objects.

 

00:08:05.000 Only then will the objects be reclaimed.

 

00:08:08.266 Reference counting stores a reference count alongside

00:08:11.100 each object, as an additional hidden field.

00:08:14.100 If the objects can be accessed concurrently,

00:08:16.633 it may also need a mutex for each object.

 

00:08:19.666 This uses additional memory. And can be

00:08:22.566 quite a high overhead if the objects are small.

 

00:08:25.733 And the processor cost of updating the

00:08:27.633 references can be moderately high, if the

00:08:30.133 program manipulates pointers a lot, of if

00:08:32.000 the objects don’t live long.

 

00:08:35.233 Despite these limitations,

00:08:36.900 reference counting is widely used.

 

00:08:39.800 It’s common in scripting languages, such as

00:08:42.500 Python or Ruby, where the overhead of

00:08:44.866 using an interpreted language far outweighs the

00:08:47.133 overhead of using reference counting.

 

00:08:50.000 It’s also used for some aspects of systems programming.

 

00:08:54.166 Applications for the iPhone and Mac are

00:08:56.700 typically written in the Objective C language.

 

00:08:59.700 This is an object oriented extension to

00:09:02.100 C that uses reference counting to manage

00:09:03.966 the memory allocated to objects. And it’s

00:09:06.966 actually highly optimised and reasonably high performance.

 

00:09:09.966 Reference counting has always been fast enough

00:09:12.333 for user interface code and much application

00:09:14.766 logic. It’s not used for low-level,

00:09:17.933 in-kernel, code, where performance is critical, though.

 

00:09:22.766 That concludes our discussion of reference counting.

 

00:09:25.766 It’s a simple, and reasonably effective automatic

00:09:28.400 memory management scheme, that’s quite widely used.

 

00:09:31.600 In the next part, I’ll move on to discuss

00:09:34.300 an alternative known as region-based memory management.

Part 3: Automatic Memory Management: Region-based Memory Management

This final part of the lecture begins to discuss region-based memory management, as used for automatic memory management in Rust. It reviews how the stack is used to manage memory for local variables, and describes how region-based memory management extends this, with the aid of extensions to the type system, to also manage heap allocated objects. The benefits and limitations of region-based approaches to memory management are discussed.

 

00:00:00.250 In this part of the lecture,

00:00:01.959 I want to introduce region-based memory management

00:00:05.041 and discuss how it's used to manage memory in Rust.

 

00:00:10.291 Region-based memory management

00:00:11.959 is a new way of managing memory

00:00:13.875 that grew out of frustrations with the alternatives.

 

00:00:17.250 Reference counting, as we saw in the last part,

00:00:20.125 is simple and easy to understand,

00:00:22.500 but has relatively high overheads.

 

00:00:25.250 It takes space to store the reference counts

00:00:27.625 and time to update them.

 

00:00:30.125 And while this overhead is okay for most applications,

00:00:33.417 it's too much for performance critical systems code.

 

00:00:37.125 Garbage collection,

00:00:38.375 which I'll talk about in detail in the next lecture,

00:00:41.333 has unpredictable timing and high memory overheads.

 

00:00:45.375 And manual memory management is too error-prone.

 

00:00:49.458 Region-based memory management aims

00:00:51.458 for the middle ground between these.

 

00:00:53.667 It aims to be safe and offer predictable timing,

00:00:57.041 and it has no runtime cost

00:00:59.166 compared to manual memory management

 

00:01:01.959 But, to achieve this,

00:01:04.208 it forces some changes in the way code is written.

 

00:01:09.291 So what is region-based memory management?

 

00:01:12.750 Well, to understand that,

00:01:14.417 let's first recap the way memory is managed on the stack.

 

00:01:19.417 The slide shows a simple C program.

 

00:01:22.959 This comprises two functions,

00:01:25.166 main() and conic_area(),

00:01:28.208 where the conic_area() function

00:01:30.375 implements a mathematical formula

00:01:32.333 to calculate the surface area of a right circular cone.

 

00:01:36.667 There's one global static variable holding the value of pi.

 

00:01:41.625 The main() function takes no parameters

00:01:44.000 and holds local variables width, height, and area.

 

00:01:48.208 And the conic_area() function takes two parameters,

00:01:51.375 w and h, and holds the local variables r and a.

 

00:01:57.250 The diagram on the right

00:01:58.875 shows the memory regions owned by the program,

00:02:01.417 while the conic_area() function is executing.

 

00:02:06.166 We see there's a region holding the global variables

00:02:09.417 and subregions for the stack frames for main()

00:02:12.291 and for the conic_area() function.

00:02:14.959 These nest, one within the other,

00:02:17.500 with the global region lasting

00:02:19.375 for the entire duration of the program,

00:02:21.792 and the other regions nesting within

00:02:24.041 and lasting for part of the time.

 

00:02:27.250 The lifetime of the local variables

00:02:29.333 and function parameters

00:02:30.708 matches that of the stack frames

00:02:32.625 of the functions holding them.

 

00:02:35.458 Memory is allocated and deallocated automatically,

00:02:38.750 efficiently and seamlessly.

 

00:02:42.834 Essentially, there's a hierarchy of regions

00:02:45.333 corresponding to the call stack of the program.

 

00:02:48.667 The lifetime of the global variables

00:02:51.041 is that of the entire program,

00:02:53.208 and the lifetime of the local variables matches

00:02:55.583 the execution time of the functions they live within.

 

00:02:59.959 And within each function,

00:03:02.000 we see there may be lexically scoped variables

00:03:04.750 hat have a lifetime less than that

00:03:06.583 of the enclosing function.

 

00:03:09.417 In the code on the slide, for example,

00:03:12.041 we see that the variable i,

00:03:13.917 the index variable in the for loop,

00:03:16.500 ives only for the duration of that loop.

 

00:03:20.583 Each of these variables lives within a region,

00:03:23.583 scoped by the program code,

00:03:25.333 and is automatically allocated when entering that region

00:03:29.041 and deallocated when the program leaves that region.

 

00:03:33.875 This works seamlessly,

00:03:36.208 so much so that we take it for granted when writing code.

 

00:03:42.125 But there's one limitation to this stack-based

00:03:44.458 approach to memory management.

 

00:03:46.750 It requires the data to be allocated on the stack.

 

00:03:51.041 In the example on this slide,

00:03:53.250 the variable tmp lives on the stack frame

00:03:55.708 for the hostname_matches() function.

 

00:03:58.917 Space for the variable is created when

00:04:00.792 the function starts to execute,

00:04:02.959 and freed when the function concludes.

 

00:04:06.834 But that's only the memory that holds tmp.

 

00:04:10.667 That is, the memory for the local variable

00:04:13.166 holding the pointer is managed automatically.

 

00:04:17.458 The heap allocated memory,

00:04:19.375 the memory allocated by the call to malloc(),

00:04:22.166 is not freed automatically.

 

00:04:25.500 When tmp goes out of scope,

00:04:27.917 the space holding the pointer is freed,

00:04:30.750 but the value it points to is not.

 

00:04:34.750 The program doesn't call free() to deallocate the memory

00:04:38.125 and it doesn't return the pointer

00:04:39.917 so some other function can do so.

 

00:04:42.875 It leaks memory.

 

00:04:44.625 The pointer is gone,

00:04:46.208 so there's no remaining reference to the allocated memory,

00:04:49.166 so there's no way to free that memory

 

00:04:55.542 Stack-based memory management is clearly effective,

00:04:59.041 but also clearly has limited applicability.

 

00:05:02.959 Can we extend it to manage the heap?

 

00:05:06.291 Well yes in principle.

 

00:05:08.208 In principle it will be straightforward

00:05:09.959 for the compiler to track pointers to heap allocated memory,

00:05:13.250 and deallocate that memory

00:05:14.917 when those pointers go out of scope.

 

00:05:18.125 And this would handle cases such as that shown on the slide,

00:05:21.583 where heap memory is allocated within a function

00:05:24.417 and should be freed when that function returns.

 

00:05:28.166 But it wouldn't handle the case where the function returns

00:05:31.583 a pointer to heap memory that it has allocated,

00:05:34.291 where the lifetime of the heap allocated memory

00:05:37.041 extends across more than one function.

 

00:05:39.333 To support such cases,

00:05:40.959 we need to move beyond stack-based memory management.

 

00:05:46.458 The extension we need

00:05:48.083 is known as region-based memory management.

 

00:05:51.583 In region-based memory management,

00:05:54.000 the compiler tracks not just the lifetime of the

00:05:56.959 stack frame in which a variable is allocated,

00:05:59.750 but also when variables are passed between stack frames.

 

00:06:04.041 That is, the compiler tracks

00:06:06.000 the lifetime of data as it's passed between functions.

 

00:06:10.291 And it tracks the region of the program

00:06:12.291 in which each piece of data is active.

 

00:06:15.333 That is, the stack memory is managed as normal,

00:06:18.458 but object lifetimes are also tracked,

00:06:20.625 and the compiler knows when each item of data

00:06:23.375 ceases to be used within the program,

00:06:25.417 either because it goes out of scope,

00:06:27.625 or because it's passed to a function but not returned.

 

00:06:31.667 The compiler can then ensure

00:06:34.083 that objects allocated on the stack

00:06:36.125 are deallocated at the end of their lifetimes.

 

00:06:41.333 Once the compiler reliably tracks object lifetimes,

00:06:44.542 it can reliably manage memory allocated on the heap.

 

00:06:48.417 If every piece of heap allocated data

00:06:51.583 has a single owner,

00:06:53.041 and the compiler tracks the lifetime of that owner,

00:06:55.959 then the heap allocated memory

00:06:57.834 can be freed at the end of the lifetime of its owner.

 

00:07:01.625 This gives an efficient,

00:07:03.750 automatic, way of managing memory on the heap.

 

00:07:08.041 And this is how memory management works in Rust.

 

00:07:11.834 Heap memory is managed using the Box type.

 

00:07:16.708 A variable of type Box

00:07:18.959 is a value that's stored on the stack

00:07:21.333 but holds a reference to an object of type T

00:07:23.834 that's allocated on the heap.

 

00:07:26.625 In the code we see on the slide,

00:07:28.750 the variable b is the Box

00:07:30.917 allocated on the stack, in the same way as any other

00:07:33.333 variable is allocated on the stack,

00:07:35.417 that internally holds a pointer to an integer

00:07:38.083 that was allocated on the heap.

 

00:07:41.291 And remember a call to Box::new(5)

00:07:45.542 allocates space to hold a single integer on the heap

00:07:48.667 and stores the number five in that space.

00:07:51.375 It doesn't allocate space for five integers.

 

00:07:55.458 The variable b is passed to the println!() macro,

00:07:58.333 and that in turn passes it to the underlying print function.

 

00:08:02.417 But the value is not returned,

00:08:04.500 so this is the end of its lifetime.

 

00:08:07.875 The compiler can therefore generate

00:08:09.875 a call to deallocate the heap memory referenced by the box,

00:08:13.125 B, immediately after the println!() call.

 

00:08:17.417 And we see that the heap allocated memory

00:08:19.542 has a lifetime matching that of the Box.

 

00:08:22.208 When the Box goes out of scope,

00:08:24.250 the referenced heap memory is also freed.

 

00:08:28.708 If you've programmed C++, this approach will be familiar.

00:08:32.583 It's the RAII, Resource Acquisition

00:08:34.959 is Initialization, Design Pattern.

 

00:08:37.625 And Python also does something similar

00:08:39.708 with its with clauses

00:08:41.208 that constrain the lifetime of a value

00:08:43.250 to a particular scope.

 

00:08:47.917 This form of region-based memory management

00:08:50.041 is how Rust manages memory.

 

00:08:53.500 To be effective,

00:08:54.625 region-based memory management has to

00:08:56.458 tie object lifetimes to stack frames,

00:08:59.125 but also to track how objects are

00:09:00.959 passed between stack frames,

00:09:03.417 and do so in a way that maintains the

00:09:05.417 single owner invariant for every object.

 

00:09:09.375 At every point,

00:09:10.625 the compiler must know what region of code owns

00:09:12.917 each piece of data.

 

00:09:15.041 And as data is passed between functions,

00:09:17.375 as ownership of the data is passed between functions,

00:09:20.458 the compiler must track that ownership.

 

00:09:24.250 And when the data items finally go out of scope,

00:09:28.166 after their ownership has been passed between functions,

00:09:31.583 only then should they be deallocated.

00:09:33.875 And only then should any heap

00:09:35.500 memory that they reference be deallocated.

 

00:09:39.041 This is the reason Rust has such complex rules

00:09:41.542 around references and ownership.

 

00:09:43.583 They enforce the constraints

00:09:45.125 needed for region-based memory management to work.

 

00:09:51.417 The resulting region-based memory management

00:09:53.875 scheme is safe and has low overhead and predictable timing.

 

00:09:59.250 It also has no runtime cost

00:10:01.333 beyond that of allocation and deallocation.

 

00:10:04.125 It doesn't need to store and update reference counts.

 

00:10:07.542 It doesn't need all the runtime complexity

00:10:09.458 and overhead of garbage collection.

 

00:10:12.291 Heap memory is managed by the compiler,

00:10:14.792 with the compiler generating code to call malloc()

00:10:17.417 when a Box is created,

00:10:19.208 and to call free() when the lifetime of the box ends,

00:10:22.458 in the same way as it would in a

00:10:24.083 correctly written C program.

 

00:10:28.000 But there is a cost.

 

00:10:30.959 And that cost is in terms of complexity of the type system

00:10:34.125 and the restrictions it imposes

00:10:35.708 on the types of program that can be written.

 

00:10:39.458 The type system in Rust is more complex

00:10:41.792 than many other languages.

 

00:10:44.000 It has several different types of pointer,

00:10:46.417 and complex rules around how references are managed

00:10:49.375 and what references can exist.

 

00:10:52.375 These rules prevent cyclic data structures,

00:10:55.166 such as doubly linked lists and graphs,

00:10:57.333 from being written in safe rust,

00:10:59.667 and they add complexity.

 

00:11:02.792 This is the trade-off.

 

00:11:05.166 Rust adds compile-time complexity,

00:11:08.083 and places restrictions on what programs can be written,

00:11:11.458 but in return offers safety and high performance.

 

00:11:16.250 Other languages reduce the complexity of the type system,

00:11:19.625 but in return lose either safety or performance.

 

00:11:24.208 The trade-off inherent in Rust

00:11:26.000 means it's not always the right language for the job,

00:11:28.834 but it does tend to fit the constraints of

00:11:30.875 systems programming quite well.

 

00:11:36.333 That concludes this introduction to

00:11:38.000 region-based memory management.

 

00:11:40.333 The key insight

00:11:41.583 is that if every value has a unique owner,

00:11:44.500 and the compiler tracks ownership

00:11:46.417 and the lifetime of those values,

00:11:48.500 then every value can be automatically

00:11:50.583 freed at the end of its lifetime.

 

00:11:53.542 This is the key difference between Rust

00:11:55.708 and other programming languages.

 

00:11:58.041 The Rust compiler knows when a value has been consumed,

00:12:01.375 when it's reached the end of its lifetime,

00:12:03.750 and will enforce this at compile time.

 

00:12:07.125 Other languages either don't track lifetimes,

00:12:09.959 like C, and potentially allow use after free bugs,

00:12:13.333 dangling references, and so on.

 

00:12:16.083 Or they use some form of garbage collection

00:12:18.708 to track liveness of data at runtime.

 

00:12:21.542 They're either unsafe or they have runtime overhead.

 

00:12:25.750 Rust is both safe

00:12:27.333 and avoids the runtime overheads,

00:12:29.458 but to achieve this,

00:12:31.083 Rust restricts the set of programs that can be expressed.

Discussion

Lecture 4 focussed on resource ownership and memory management. It started by discussing how a process is laid out in memory, and what memory needs to be managed. Then, it moved on to discuss the problem of, and need for, automatic memory management in general terms, highlighting that systems programmers tend to distrust automatic memory management, yet suffer from the problems due to manual memory management.

The lecture then discussed reference counting. This is widely used in both scripting languages, such as Python or Ruby, and in the Objective-C runtime used on Apple's iPhone and Mac operating systems. It noted that reference counting is relatively easy to understand, incremental, and predictable, but suffers from relatively high overhead with small or short-lived objects, and cannot collect cyclic data structures.

The lecture then focussed on the region-based memory management scheme used by Rust. It noted that the language tracks ownership of data as it moves between functions, and deterministically cleans up heap allocated memory when the lifetime of an object ends. Region based memory management achieves good, predictable, performance, and provides a number of nice guarantees around absence of race conditions, use-after-free bugs, iterator invalidation, and so on. But it comes at the cost of making the type system considerably more complex, and in limiting the types of programs that can be expressed.

Discussion will focus, primarily, on how the region based memory management scheme works, and on its advantages and disadvantages compared to other approaches. The goal is to understand whether you think the benefits outweigh the complexity introduced.