Rework list implementation

Fixes memory leaks, adds error handling, allows more optimizations for
compiler.