Fix possible memory leaks while using 'realloc'

These issues were found with [cppcheck](http://cppcheck.sourceforge.net/) static analysis tool.