Fix: refactor function that fixes memory leak also

Signed-off-by: David Goulet <dgoulet@efficios.com>