check return values of malloc and handle error.

added some missing includes, too.

closes #199.
fix NULL check
Merge pull request #200 from jan-schreib/check_malloc

check return values of malloc and handle error.