Could not figure out how to get rid of dangling pointer