fix segfault and avoid unnecessary string copying