check return values of malloc and handle error.

added some missing includes, too.

closes #199.