Adding malloc safety check for NULL

Hi,

A static scan of our application reported this "flaw" where the return value of `malloc` is not checked against `NULL`.
I would appreciate if you would accept this pull request.

Thanks