This is a broken out patch from #3984. It does not fix the doctest, but numerous issues valgrind picks up. Someone needs to remember that C strings are NULL terminated :)
Cheers,
Michael
Component: memleak
Issue created by migration from https://trac.sagemath.org/ticket/4067