mem: extract common dynamic memory allocation