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

C++ Memory Leak - What do I delete, and where?

本文关键字:删除 什么 在哪里 内存 泄漏 C++      更新时间:2023-10-16

以下函数中存在内存泄漏。我遇到的麻烦是知道如何,何时,何地以及删除什么。这是代码:

#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;
}

如您所见,我尝试了删除使用后分配的新数组的方法。这不起作用实际上是有道理的,但我不确定在这里做什么。.

新增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;
}

在这种情况下,这是否解决了任何内存泄漏?

您正在分配和删除函数中的数组。你也归还了它。

int main()
{

这个是在堆栈上分配的,所以退出main()时会被删除

    double dbls[] = { 1, 2, 3, 4, 5 };
    double* pArray = dbls;
    //...

你的函数分配了一些内存,现在由 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){ }

你忘了删除函数分配的内存!!内存泄漏!!!

    return 0;
}

在这里:

*ppDoubleArray = pNewDoubleArray;
delete[] pNewDoubleArray;

删除刚刚传递回调用方的数组。不要这样做删除!在将内存传回后,由调用方来管理内存。

与其跳过所有这些箍,不如考虑编写"真正的"C++代码,使用像std::vector这样的容器对象来管理内存。

你的意思是这样做吗:

void someFunc(double** ppDoubleArray, int length)
{
     for(int i = 0; i < length; i++)
    {
        *ppDoubleArray[i] = 3 * i + 2;
    }
}

我不明白,如果您的目的是修改传入的数组,为什么要分配一个新数组。

someFunc中,您分配数组,然后设置用户传递的指针以指向它。退出函数后,删除该数组,用户最终会有一个指向释放内存的指针。

您无法delete pNewDoubleArray,因为您将它的地址存储在 ppDoubleArray 中。您必须 delete[] pArray ,当它不再使用或将其设置为另一个地址之前(再次调用someFunc(&pArray, ...)时)。