Replace malloc() with mem_alloc() in many places.
Improve max-length self-test so it better reflects real world.