Don't allocate memory until you know you're going to use it and arrange for
it to be freed.  Leak!
Tidy the code and add a test.