                         in.dims()[0], in.dims()[1], nNZ,
                         converted.getRowIdx().get(), converted.getColIdx().get(),
                         &pBufferSizeInBytes));
-        char *pBuffer = memAlloc<char>(pBufferSizeInBytes);
-
-        int *P = memAlloc<int>(nNZ);
-        CUSPARSE_CHECK_FREE(cusparseCreateIdentityPermutation(getHandle(), nNZ, P));
-
-        CUSPARSE_CHECK_FREE(cusparseXcoosortByColumn(
-                            getHandle(),
-                            in.dims()[0], in.dims()[1], nNZ,
-                            converted.getRowIdx().get(), converted.getColIdx().get(),
-                            P, (void*)pBuffer));
-
-        CUSPARSE_CHECK_FREE(gthr_func<T>()(
-                            getHandle(), nNZ,
-                            in.getValues().get(),
-                            converted.getValues().get(),
-                            P, CUSPARSE_INDEX_BASE_ZERO));
-
-        memFree(P);
-        memFree(pBuffer);
+        shared_ptr<char> pBuffer(memAlloc<char>(pBufferSizeInBytes), memFree<char>);
+
+        shared_ptr<int> P(memAlloc<int>(nNZ), memFree<int>);
+        CUSPARSE_CHECK(cusparseCreateIdentityPermutation(getHandle(), nNZ, P.get()));
+
+        CUSPARSE_CHECK(cusparseXcoosortByColumn(
+                       getHandle(),
+                       in.dims()[0], in.dims()[1], nNZ,
+                       converted.getRowIdx().get(), converted.getColIdx().get(),
+                       P.get(), (void*)pBuffer.get()));
+
+        CUSPARSE_CHECK(gthr_func<T>()(
+                       getHandle(), nNZ,
+                       in.getValues().get(),
+                       converted.getValues().get(),
+                       P.get(), CUSPARSE_INDEX_BASE_ZERO));
 
     } else if (src == AF_STORAGE_COO && dest == AF_STORAGE_CSR) {
         // The cusparse csr sort function is not behaving correctly.


    return converted;
}

#undef CUSPARSE_CHECK_FREE


#define INSTANTIATE_TO_STORAGE(T, S)                                                                        \
    template SparseArray<T> sparseConvertStorageToStorage<T, S, AF_STORAGE_CSR>(const SparseArray<T> &in);  \

    return dense;
}

template<typename T, af_storage dest, af_storage src>
SparseArray<T> sparseConvertStorageToStorage(const SparseArray<T> &in)
{
    using boost::shared_ptr;
    in.eval();

    int nNZ = in.getNNZ();
