vendredi 2 mars 2018

What's wrong with delete [] arrays in C++

I'm just learning C++, so please be patient, if I ask something stupid (smile). I'm trying this piece of code. It's working ok in two cases: I don't try to delete the dynamic array that is created recently in this code or I do some tricks to make it work.

The (bubble) sorting algorithm works fine until I decide to prevent memory leak by deleting the array after all the work on it is done. But suddenly it happens that my cool sorting algorithm stops working! In fact only two elements of the array are swapped before its content is shown to the frustrating user (me).

I found that adding some elements to the program (commented lines) solves the problem — array is shown sorted. So I got two questions:

  1. Is this behavior normal or not?
  2. If this is normal, what should I do to predict such a non-obvious behavior and not to get into a situation when I will be sure that the object is in a particular state but in fact it is in another (deleted "in advance")?
int arr_len;
int *arr;
// bool sorting_complete = false;

arr_len = some_action();
arr = new int[arr_len];

/* ...
   Filling the array with random integers 
   ... 
*/

cout << "Array before sorting: ";
for (int i = 0; i < arr_len; i++)
    cout << arr[i] << " ";
cout << endl;

for (int i = 0, max = arr_len - 1; i < max; ++i)
    for (int j = i + 1; j < arr_len; j++)
        if (arr[i] < arr[j])
            swap(arr[i], arr[j]);

// sorting_complete = true;

cout << "Array after sorting: ";
for (int i = 0; i < arr_len; i++)
    cout << arr[i] << " ";
cout << endl;

// if (sorting_complete)
    delete [] arr;

Because of the fact that I'm not that experienced in C++ guy, I guess it's not the problem of the compiler (I'm using g++) but, more likely, of my hands. Could you guys help me to figure out what wrong with this code?

Aucun commentaire:

Enregistrer un commentaire