Check memory allocation
Declare vars as locally as possible
Merge pull request #421 from asmaloney:check-mem-alloc2