Debug assertion failed when trying to delete array from heap

Viewed 42

I have a sub-optimal solution to return two variables from a function by creating a pointer to an array with two indexes. (just using my current knowledge base from class. I know vectors or std::pair would be a better solution)

However, when I try to delete the array via the pointer, I'm getting the below error.

Am I misunderstanding the procedure? Is this array not created in heap and therefore no need for explicit deletion?

Edit: Quick Comment

thanks to those that are providing more ideal formulations for the type of problem I'm trying to solve. I am (was) just trying to understand the specific behavior of this error I was getting.

I realize this is not an optimal way to store two variables. Just code to experiment with some features of C++. Feel free to provide better formulations for the general benefit of others.

enter image description here

#include <iostream>
#include <cmath>

double* quadraticEquation(double a, double b, double c) {
    double x1, x2;

    x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);
    x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);
    double arr[2] = {x1, x2};
    return arr;
}

int main()
{
    double* solution = quadraticEquation(3, 5, -8);

    double x1 = solution[0];
    double x2 = solution[1];
    std::cout << "x1 = " << x1 << std::endl << "x2 = " << x2 << std::endl;

    delete[] solution;
    solution = nullptr;
}
1 Answers

You should return heap allocated memory. You could use new double[2] or a smart pointer.

double* quadraticEquation(double a, double b, double c) {
  double x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);
  double x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);
  return new double[2]{x1, x2};
}

With smart pointers you don't need to remember to deallocate the heap memory, the usage looks like this.

std::unique_ptr<double[]> quadraticEquationSmartPointer(double a, double b, double c) {
  double x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);
  double x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);
  return std::unique_ptr<double[]>(new double[2]{x1, x2});
}

int main() {
  auto solution = quadraticEquationSmartPointer(3, 5, -8);
  double x1 = solution[0];
  double x2 = solution[1];
  std::cout << "x1 = " << x1 << std::endl << "x2 = " << x2 << std::endl;
}

But in this case it would be easier to just return a std::pair<double, double> or a std::tuple<double, double>, also more secure, as it gives you the number of values you should expect.

With pair is even easier.

std::pair<double, double> quadraticEquationPair(double a, double b, double c) {
  double x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);
  double x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);
  return std::make_pair(x1, x2);
}

int main() {
  auto [x1, x2] = quadraticEquationPair(3, 5, -8);
  std::cout << "x1 = " << x1 << std::endl << "x2 = " << x2 << std::endl;
}
Related