Fix memory allocation size mismatch and memory leaks :droplet: