Try freeing it only when its valid and assign a null by default so you know if its not null you free it.