Remove memory leak and unnecessary allocation
(cherry picked from commit c998f7b81fb7a846b60006a3d74985a53b88cc0e)