Rust Brain Teasers: leaking loop running forever? (page 50)

The author apparently contradicts himself, since in the discussion it becomes apparent that the program will be terminated after running for a while. So it’s definitely not running forever, and that’s the surprise in this puzzle.

The “Amnesia” teaser really is a double-layered puzzle, structured to teach the reader about a common Rust misconception.

A loop without a break will run forever (in as much as any process can run forever; eventually it’ll be terminated). So that’s not meant to be surprising: you can see there’s a loop and no break or terminate, panic or other process ending call.

In this case, it’s quietly leaking just under 4k of RAM per loop iteration–so eventually it will grind to a halt, and depending upon your Operating System’s “OOM killer” setup may be terminated.

The real surprise—and purpose of the teaser, from a teaching point of view—is to highlight that Rust’s extensive memory guarantees explicitly do not include protection from memory leaks. The language makes it tricky to accidentally leak memory, but it can be done. Even more surprisingly, forget and its ilk explicitly create memory leaks! That seems to fly in the face of what is expected from “memory safety”–so the discussion leads into covering why a) this isn’t a guarantee, and b) you may occasionally actually want to leak memory.

I hope that clears up the thought process a bit.

1 Like