如何删除函数中创建的动态数组

时间:2019-07-29 11:25:00

标签: c++ memory dynamic

我必须编写一个程序(不使用向量,也不使用结构或OOP)来计算两个多项式的和与乘积。 这是我的代码:

//Task 4.19 & 4.20
#include <iostream>
#include <cmath>
double* definePoly(char& symbol, char& coef, int& k)
{
    std::cout << "deg(" << symbol << "(x)) = ";
    std::cin >> k;
    symbol++;
    double* a = new double[k];
    for (int i = k; i >= 0; i--)
    {
        std::cout << coef << "_{" << i << "} = ";
        std::cin >> a[i];
    }
    coef++;
    return a;
}
void printPoly(int n, double* P, char& symbol)
{
    symbol--;
    std::cout << symbol << "(x)=";
    for (int i = n; i >= 0; i--)
    {
        if (P[i] != 0)
        {
            if (P[i] > 0)
            {
                std::cout << '+';
            }
            std::cout.setf(std::ios::fixed);
            std::cout.precision(2);
            std::cout << P[i] << ".x^{" << i << "}";
        }
    }
    std::cout << "\n";
    symbol++;
}
double* sumPoly(double* a, int n, double* b, int m, char& symbol)
{ // Task 4.19
    symbol++;
    double* c = new double[(n + m + abs(n - m)) / 2];
    if (n > m)
    {
        for (int i = 0; i <= m; i++) c[i] = a[i] + b[i];
        for (int i = m + 1; i <= n; i++) c[i] = a[i];
    }
    else if (n < m)
    {
        for (int i = 0; i <= n; i++) c[i] = a[i] + b[i];
        for (int i = n + 1; i <= m; i++) c[i] = b[i];
    }
    else for (int i = 0; i <= n; i++)c[i] = a[i] + b[i];
    return c;
}
double* prodPoly(double* a, int n, double* b, int m, char& symbol)
{ // Task 4.20
    symbol++;
    double* d = new double[n + m];
    for (int p = 0; p <= n + m; p++)
    {
        d[p] = 0;
        for (int i = 0; i <= n; i++)
            for (int j = 0; j <= m; j++)
                if (i + j == p) d[p] = d[p] + a[i] * b[j];
    }
    return d;
}
int main()
{
    int n, m;
    char symbol('P'), coef('a');

    double* firstPoly = definePoly(symbol, coef, n);
    printPoly(n, firstPoly, symbol);

    double* secondPoly = definePoly(symbol, coef, m);
    printPoly(m, secondPoly, symbol);

    double* sum = sumPoly(firstPoly, n, secondPoly, m, symbol);
    std::cout << "Sum:\n";
    printPoly((n + m + abs(n - m)) / 2, sum, symbol);

    double* prod = prodPoly(firstPoly, n, secondPoly, m, symbol);
    std::cout << "Product:\n";
    printPoly(n + m, prod, symbol);

    /*delete[] firstPoly;
    delete[] secondPoly;
    delete[] sum;
    delete[] prod;*/

    return 0;
}

它完全可以正常工作,但是当我取消注释删除时,Visual Studio告诉我有错误,否则有泄漏。

如何删除/释放内存以解决此问题?

1 个答案:

答案 0 :(得分:7)

double* a = new double[k];
for (int i = k;
    std::cin >> a[i];

k元素数组的最后一个元素的索引为k - 1,您可以在所有循环中无限制地访问数组(这只是其中之一)。该程序的行为是不确定的。

  

如何删除在函数中创建的动态数组

就像您将删除在函数外部创建的动态数组一样,就像您试图删除它一样:

delete[] firstPoly; // etc

但是您必须确保您的程序不会以未定义的行为破坏其自身的内存。