to_dense() method modified to remove memory leaks