add constant for max tries and correct memory leaks