Safeguard against elem == NULL

This should not normally happen but in theory it can (if match wraps
around in the match++ instruction).
Skip realloc and elem access for elem_len == 0

Besides obvious benefits, this prevents passing NULL to strncat().
Fix memory leak and handle failure of pathspec formatting