Fixes TW8162. Associated test case is run under Instruments on macOS, until I set up valgrind to test this automatically on Linux.