modules/utils: fixed memory leak and possible crash

- patch against 4.0 was provided by Guillaume Bour
(cherry picked from commit 92b947059dbde8ada3c757d7e6af48d79f9e7e12)