This function avoids some unecessary memory allocation. The memory alloc'd by this function must be freed later by the caller. (cherry picked from commit 8651174861657b9d99b741b1ffe12ff164284e4e)