jeudi 24 octobre 2019

Why would the for loop in the below code produce a double free or corruption (fasttop) error?

This program shows the error in the title when finishing the 3rd iteration (terminates when i becomes 3). I have couts for when the program terminates and the final cout occurs after the final i when i = 2 and the before the first i when i equals 3. Why would the iteration from the third array to the fourth cause a double free or corruption?

    int main(int argc, char* argv[])
{

  std::ifstream inFile;

  inFile.open(argv[1]);

  if(!inFile.is_open())
  {

    std::cout << "File could not be opened" << '\n';

    return 0;

  }

  int n = 0;

  inFile >> n;

  std::cout << n <<std::endl;

for(int i = 0; i < n; i++)
{
    std::cout << i << std::endl;
  int m;

  inFile >> m;

  int* arr = new int[m];

  std::cout << "Unsorted list:" << std::endl;
std::cout << i << std::endl; 
  for(int j = 0; j < m; j++)
  {

    inFile >> arr[j];

    std::cout << arr[j] << ' ';

  }

  std::cout << std::endl;
std::cout << i << std::endl;
  BubbleSort<int> bubble = BubbleSort<int>(m, arr);
  bubble.sort();

  InsertionSort<int> insert = InsertionSort<int>(m, arr);
  insert.sort();

  SelectionSort<int> select = SelectionSort<int>(m, arr);
  select.sort();

  std::cout << "Sorted Lists:" << '\n';

  std::cout << "Bubble:" << '\n';
  bubble.printArray();

  std::cout << "Insertion: " << '\n';
  insert.printArray();

  std::cout << "Selection: " << '\n';
  select.printArray();

  delete[] arr;
std::cout << i << std::endl;

}
  return 0;

}

Aucun commentaire:

Enregistrer un commentaire