fix bug 1142175/1142181: handle potential memory leak and NPE issues