add defer to prevent memory leaks