fixed memory leaks in functions called in templates