Fix memory leaks by avoiding extra manual dynamic allocation