My attempt at preventing memory leaks