C++内存泄漏 - 我删除什么,在哪里?

Min*_*wth 2 c++ pointers memory-leaks memory-management

以下函数中存在内存泄漏.我遇到的麻烦是知道删除的方式,时间,地点和内容.这是代码:

#include "stdafx.h"
#include <iostream>

void someFunc(double** ppDoubleArray, int length)
{
    double* pNewDoubleArray = new double[length];

    for(int i = 0; i < length; i++)
    {
        pNewDoubleArray[i] = 3 * i + 2;
    }

    *ppDoubleArray = pNewDoubleArray;
}
int main()
{
    double dbls[] = { 1, 2, 3, 4, 5 };
    double* pArray = dbls;

    int length = sizeof dbls / sizeof dbls[0];

    std::cout << "Before..." << std::endl;

    for(int i = 0; i < length; i++)
    {
        std::cout << pArray[i] << ", ";
    }

    std::cout << std::endl;

    someFunc(&pArray, length);

    std::cout << "After..." << std::endl;

    //Expected series is: 2, 5, 8, 11, 14

    for(int i = 0; i < length; i++)
    {
        std::cout << pArray[i] << ", ";
    }

    std::cout << std::endl;

    while(true){ }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我尝试删除使用它后分配的新数组.这实际上是有道理的,但这不起作用,但我不知道该怎么做..

补充delete[] pArray:

#include "stdafx.h"
#include <iostream>

void someFunc(double** ppDoubleArray, int length)
{
    double* pNewDoubleArray = new double[length];

    for(int i = 0; i < length; i++)
    {
        pNewDoubleArray[i] = 3 * i + 2;
    }

    *ppDoubleArray = pNewDoubleArray;
}
int main()
{
    double dbls[] = { 1, 2, 3, 4, 5 };
    double* pArray = dbls;

    int length = sizeof dbls / sizeof dbls[0];

    std::cout << "Before..." << std::endl;

    for(int i = 0; i < length; i++)
    {
        std::cout << pArray[i] << ", ";
    }

    std::cout << std::endl;

    someFunc(&pArray, length);

    std::cout << "After..." << std::endl;

    //Expected series is: 2, 5, 8, 11, 14

    for(int i = 0; i < length; i++)
    {
        std::cout << pArray[i] << ", ";
    }

    delete[] pArray;

    std::cout << std::endl;

    while(true){ }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果在这种情况下所有内存泄漏,这是否会解决?

Vin*_*rat 6

您正在分配和删除函数中的数组.你也回来了.

int main()
{
Run Code Online (Sandbox Code Playgroud)

//这个在堆栈上分配,因此在退出main()时会被删除

    double dbls[] = { 1, 2, 3, 4, 5 };

    double* pArray = dbls;

    //...
Run Code Online (Sandbox Code Playgroud)

//你的函数分配了pArray现在指向的一些内存

    someFunc(&pArray, length);

    std::cout << "After..." << std::endl;

    //Expected series is: 2, 5, 8, 11, 14

    for(int i = 0; i < length; i++)
    {
        std::cout << pArray[i] << ", ";
    }

    std::cout << std::endl;

    while(true){ }
Run Code Online (Sandbox Code Playgroud)

//你忘了删除你的功能分配的内存!内存泄漏!!!

    return 0;
}
Run Code Online (Sandbox Code Playgroud)