Question: I am using MVC 4.

I have a method in my controller which generates a CSV file on demand and I want this file to be then downloaded by the user without the need of saving it to the disk at the server side. So I am passing a MemoryStream on the File() object to avoid having to firstly save file to disk and later give him the path for download.

Controller Method:

```
[HttpGet]
public ActionResult GenerateCsv(string data)

    var sb = new StringBuilder();
    sb = GetCsvReportToString(data);

    var stream = new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString()));

    return this.File(stream, "text/csv", "ReportCsv.csv");
}

```

sb (StringBuilder) has the correct data, as I have debugged it and confirmed it.

my javascript code:

```
window.open(generateFileLink + '?data=' + dataToSend, '_blank');

```

The window gets in fact opened, the download dialog appears but with an error, saying that it cannot be downloaded from localhost:

![enter image description here](https://i.stack.imgur.com/GQfWh.png)

The name is different in the download "ReportToCsv" because I didn't use real names for methods in my question, but doesn't matter.

Can anyone assist?

Answer: 
```
for(unsigned int i = x_str.length(); i > 0; i++)

```

This is the problem line.

See what happens to the variable `i` when you execute this loop. Try running it step by step.

```
for(unsigned int i = x_str.length(); i > 0; i++){
    std::cerr << "i =" << i << std::endl;
    x_str_rev += x_str[i];
};

```

Learning to spot indexing issues is a big part of resolving segfault issues such as this.
You have a loop that iterates over the chars in your string. But you *increment* `i` instead of decrementing:

```
for(unsigned int i = x_str.length(); i > 0; i++)

```

So this is 

1. an infinite loop
2. Accesses an invalid index inside `x_str`. That's the reason for your segfault.

You have to start at `length()-1` and use `i--` instead to get it working.

**In the future:** Learn how to use a debugger. It will readily show you the line of code where a segmentation fault or similar is happening. And it's a skill you need to master anyway, if you're serious about programming.

For example, if your on Linux, you could have done the following:

```
gdb your-program
(gdb) run 
(gdb) bt

```

And it would have shown you where the segfault happens (if compiled with debugging symbols and without optimizations).