Fix double-free and deallocator mismatch.
Fix potential mem leak.
Fix out-of-bounds memory accesses.

And remove a variable-length-array usage.
Fix/improve dereference-before-null-checks.