Factorize memory allocation code