Added guards around free and malloc due to memory issues