Repository: pytorch
Issue: free(): invalid pointer Aborted (core dumped)
Labels: needs reproduction,triaged

## 🐛 Bug
I'm trying to run a simple network however, I run the program and it I get right a way the error:
free(): invalid pointer
Aborted (core dumped)
it doen't tells me where exactly is the problem. 

## To Reproduce
You have to download to library from the git repository of fwilliams (https://github.com/fwilliams)  fml and point_cloud_utils. And run the following code:
main.py :
```python
import argparse
import point_cloud_utils as pcu
import time

import numpy as np
import torch
import torch.nn as nn
from fml.nn import SinkhornLoss

import common

print(torch.__version__)

def main():
    argparser = argparse.ArgumentParser()
    argparser.add_argument("mesh_filename", type=str, help="Point cloud to reconstruct")
    argparser.add_argument("--max-sinkhorn-iters", "-si", type=int, default=32,
                           help="Maximum number of Sinkhorn iterations")
    argparser.add_argument("--sinkhorn-eps", "-se", type=float, default=1e-3,
                           help="Maximum number of Sinkhorn iterations")
    argparser.add_argument("--learning-rate", "-lr", type=float, default=1e-3, help="Step size for gradient descent")
    argparser.add_argument("--num-epochs", "-n", type=int, default=250, help="Number of training epochs")
    argparser.add_argument("--device", "-d", type=str, default="cuda")
    argparser.add_argument("--seed", "-s", type=int, default=-1)
    args = argparser.parse_args()

    if args.seed > 0:
        seed = args.seed
        common.seed_everything(seed)
    else:
        seed = np.random.randint(0, 2**32-1)
        common.seed_everything(seed)
    print("Using seed %d" % seed)

    
    # x is a tensor of shape [n, 3] containing the positions of the vertices that
    x = torch._C.from_numpy(common.loadpointcloud(args.mesh_filename)).to(args.device)
    # t is a tensor of shape [n, 3] containing a set of nicely distributed samples in the unit cube
    v, f = common.unit_cube()
    t = torch._C.sample_mesh_lloyd(pcu.lloyd(v,f,x.shape[0]).astype(np.float32)).to(args.device) # sample randomly a point cloud (cube for now?)

    # The model is a simple fully connected network mapping a 3D parameter point to 3D
    phi = common.MLP(in_dim=3, out_dim=3).to(args.device)

    # Eps is 1/lambda and max_iters is the maximum number of Sinkhorn iterations to do
    emd_loss_fun = SinkhornLoss(eps=args.sinkhorn_eps, max_iters=args.max_sinkhorn_iters,
                                stop_thresh=1e-3, return_transport_matrix=True)

    mse_loss_fun = torch.nn.MSELoss()

    # Adam optimizer at first
    optimizer = torch.optim.Adam(phi.parameters(), lr=args.learning_rate)

    fit_start_time = time.time()

    for epoch in range(args.num_epochs):
        optimizer.zero_grad()

        # Do the forward pass of the neural net, evaluating the function at the parametric points
        y = phi(t)

        # Compute the Sinkhorn divergence between the reconstruction*(using the francis library) and the target
        # NOTE: The Sinkhorn function expects a batch of b point sets (i.e. tensors of shape [b, n, 3])
        # since we only have 1, we unsqueeze so x and y have dimension [1, n, 3]
        with torch.no_grad():
            _, P = emd_loss_fun(phi(t).unsqueeze(0), x.unsqueeze(0))

        # Project the transport matrix onto the space of permutation matrices and compute the L-2 loss
        # between the permuted points
        loss = mse_loss_fun(y[P.squeeze().max(0)[1], :], x)
        # loss = mse_loss_fun(P.squeeze() @ y,  x)  # Use the transport matrix directly

        # Take an optimizer step
        loss.backward()
        optimizer.step()

        print("Epoch %d, loss = %f" % (epoch, loss.item()))

    fit_end_time = time.time()

    print("Total time = %f" % (fit_end_time - fit_start_time))
    # Plot the ground truth, reconstructed points, and a mesh representing the fitted function, phi
    common.visualitation(x,t,phi)
    


if __name__ == "__main__":
    main()
```
common.py :
```python
from __future__ import absolute_import, division, print_function

import pathlib

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import socket
import math
import os
import sys

import numpy as np
import torch
import torch.nn as nn
import point_cloud_utils as pcu
import open3d

print(torch.__version__)

class MLP(nn.Module):
    def __init__(self, in_dim: int, out_dim: int):
        super().__init__()
        self.in_dim = in_dim
        self.out_dim = out_dim
        self.fc1 = nn.Linear(in_dim, 128)
        self.fc2 = nn.Linear(128, 256)
        self.fc3 = nn.Linear(256, 512)
        self.fc4 = nn.Linear(512, 512)
        self.fc5 = nn.Linear(512, out_dim)
        self.relu = nn.LeakyReLU()

    def forward(self, x):
        x = self.relu(self.fc1(x))
        x = self.relu(self.fc2(x))
        x = self.relu(self.fc3(x))
        x = self.relu(self.fc4(x))
        x = self.fc5(x)
        return x

def loadpointcloud(file_name):
    """
    Returns an array [n, 3] n the number of vertices. 
    :param file_name: The name of the mesh file to load
    :return: An [n, 3] array of vertex positions

    """
    data = []
    #Open and save data
    file = open("sphere.txt", "r") 
    for line in file: 
        data.append(line.split())
    file.close()

    # getting rid of empty lines
    data = list(filter(None, data))

    #getting rid of header
    del data[0] 
    
    newdata = []
    # safe only the vertices
    for line in range(0,len(data)):
        if len(data[line]) == 3:
            newdata.append(data[line])

    #mapping from string to float
    for line in range(0,len(newdata)):
        newdata[line] =list(map(float,newdata[line]))

    # Transform it to an array
    x=np.array([np.array(sli) for sli in newdata])
    
    
    return x


#define cube mesh to sample it
def unit_cube(): 
    mesh_box = o3d.geometry.create_mesh_box(width=1.0, height=1.0, depth=1.0)
    mesh_box.compute_vertex_normals()
    v = np.asarray(mesh_box.vertices)
    f = np.asarray(mesh_box.triangles)

    return v, f

# draw point cloud and contours
def visualitation(x,t,phi):
    
    slice_points = x
    recon_vertices = phi(t)

    recon_color = np.array([0.7, 0.1, 0.1])
    slices_color = np.array([0.1, 0.7, 0.1])

    pcloud_recon = open3d.PointCloud()
    pcloud_recon.points = open3d.Vector3dVector(recon_vertices)
    pcloud_recon.paint_uniform_color(recon_color)

    pcloud_slices = open3d.PointCloud()
    pcloud_recon.points = open3d.Vector3dVector(slice_points)
    pcloud_recon.paint_uniform_color(slices_color)
    
    open3d.visualization.draw_geometries([pcloud_recon, pcloud_slices])


def seed_everything(seed):
    if seed < 0:
        seed = np.random.randint(np.iinfo(np.int32).max)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    np.random.seed(seed)
    random.seed(seed)

    return seed
```

## Expected behavior
I would expect that the network would run however the code doesn't even run and I don't know where I can find which part of the code is at fault. First I tried to see if the size of the tensor where correct and I do believe they are. 

It should create a reconstruction from cross-sections of a 3d object, the output should be a point cloud.
 
## Environment
 - PyTorch Version > 1.1.0
 - Ubuntu: 18
 - How I installed PyTorch: conda
 - Python version: 3
 - CUDA/cuDNN version: V9.1.85
 - GPU models and configuration: Nvidia GTX 1050 Ti

## Additional context

You can find the sphere file here. 
[sphere.txt](https://github.com/pytorch/pytorch/files/3228078/sphere.txt)