Use strncpy to not overflow the buffer
Fix resource leaks