The code is rather unsafe. Some issues, not only about the safety but some of these certainly can cause your crash:
- Input arguments should be
const
pointers, for clarity. - The return value of
malloc()
is not checked, so if the allocation fails you're toast. - Don't cast the return value of
malloc()
in C. - Don't copy using a loop, use
memcpy()
. - There's no guarantee that
j
doesn't go out of bounds. - The
ret
array is never used.