I have a piece of C++ code that generates a bunch of sorted .txt files of varying sizes. The maximum size is 1 million. After I compile this with g++ and run it, the code generates all the files but crashes with a segmentation fault. This happens for ListSize=20 or greater. Why is this happening?
#include<iostream>
#include<cmath>
#include<fstream>
#include<cstdlib>
using namespace std;
void mergeSort(int a[], int a_tmp[], int l, int r)
{
    int i, j, k, m;
    if (r > l)
      {
        m = (r+l)/2;
        mergeSort(a, a_tmp, l, m);
        mergeSort(a,a_tmp, m+1, r);
        for (i = m+1; i > l; i--){
          a_tmp[i-1] = a[i-1];
        }
        for (j = m; j < r; j++){
          a_tmp[r+m-j] = a[j+1];
        }
        for (k = l; k <= r; k++){
          a[k] = (a_tmp[i] < a_tmp[j]) ? a_tmp[i++] : a_tmp[j--];
        }
      }
  }
int main()
{
    srand(time(0));
    int listsize[22];
    int i=0;
    int j=0;
    for (i=0;i<22;i++) {
        listsize[i]=(pow((i%3),2) + 1)pow(10,floor((i/3)));
    }
    for (i=0;i<22;i++) {
        int temporary=listsize[i];
        int a[temporary];
        int a_tmp[temporary];
        char FileName[80];
        sprintf(FileName,"testSorted%d.txt",temporary);
        ofstream outfile(FileName);
        for(j = 0;j<temporary;j++){
        a[j] = (rand() +1)%10000000;
        }
     mergeSort(a,  a_tmp, 0, temporary-1);
    for (i=0;i<22;i++) {
        listsize[i]=(pow((i%3),2) + 1)pow(10,floor((i/3)));
    }
    for (i=0;i<22;i++) {
        int temporary=listsize[i];
        int a[temporary];
        int a_tmp[temporary];
        char FileName[80];
        sprintf(FileName,"testSorted%d.txt",temporary);
        ofstream outfile(FileName);
        for(j = 0;j<temporary;j++){
        a[j] = (rand() +1)%10000000;
        }
     mergeSort(a,  a_tmp, 0, temporary-1);
    outfile << temporary << endl;
    for(j = 0;j<temporary;j++)
        outfile << a[j] << endl;
    outfile.close();
    }
    return 0;
}
}
