query function revised, memory leak fixed