A breakpoint instruction __debugbreak was executed, and i don't understand why

1.7k Views Asked by At

It is being called at the end of program, in the "delete" sequence, I guess. The program is working well all the way, except the end.

#include <iostream>
#include <cmath>
//Завдання 2, покажчикі
using namespace std;
int main()
{
    int n = 10;
    cout << "Input N (size of arrays): ";
    cin >> n;
    float* X = new float[n+1];
    float* A = new float[n + 1];
    float* max;
    float* B = new float[n];
    cout << "Input your X array (10 elems): " << endl;
    //Логарифм від нуля завжди буде нескінченністю, отже, маємо рахувати з 1
    for (int i = 1; i <= n; i++) {
        cin >> X[i];
        A[i] = cos(pow(X[i], 2)) + 4.5 * pow(log(pow(i, 2)), 2) + i;
    }
    max = new float( A[1]);
    cout << "Your A array: " << endl;
    for (int i = 1; i <= n;i++) {
        if (A[i] > *max) max = &A[i];
        cout << A[i] << " ";
    }
    cout << "\nYour B array: " << endl;
    for (int i = 0; i < n; i++) {
        B[i] = A[i + 1] / *max;
        cout << B[i] << " ";
    }
    delete max;
    delete[] X, A, B;
}

I tried to initialize max at the begining, giving it value of &A[0] (I know arrays are filled with random values when initialized, it doesn't matter). Then, I tried to initialize it in the first "for" loop like:

for (int i = 1; i <= n; i++) {
        cin >> X[i];
        A[i] = cos(pow(X[i], 2)) + 4.5 * pow(log(pow(i, 2)), 2) + i;
if (i == 1) max = &A[i];
else if (A[i] > *max) max = &A[i]; 
    }
1

There are 1 best solutions below

0
On

You have already being told in comment that your code does not follow best practices and will be hard to read and maintain. I had to read it many times to understand what it does...

The cause of the error is the delete max; instruction. You know that you must have a delete per new, but you are expected to delete what have been allocate with new. And you change the value of max (not *max) in this code... So:

  • you leak the original allocated float object (not direct cause of the error but can lead to headaches in long running programs)
  • you try to delete an variable that was not allocated with new (direct cause)

I cannot understand why you have to use an allocated float instead of a simple variable, but as you already explained that you had to mix one and zero base indexing (which is a guarantee for later problems...), I will not go that way. But you must save the address of the allocated float and use it later to delete the object:

...
float* max, *max0;
...
max0 = max = new float( A[1]);
...
delete max0;
...

But IMHO this will only fix the current error, while you should considere rewriting to full piece of code in respect of best practices...