C++更正内存泄漏

C++ correcting a memory leak

本文关键字:泄漏 内存 C++      更新时间:2023-10-16

有人可以帮我弄清楚如何重用一块分配的内存吗?此代码的最终结果应该是对第一个数组初始化和第二个数组初始化使用相同的位置。数组大小为 const 5。

编辑:我想通了。我只需要使用free(nArray);就在"nArray = new int[arraySize + 2];"行之前,这允许我纠正泄漏并重用相同的内存位置。

int main()
{
    cout << endl << endl;
    int* nArray = new int[arraySize];
    cout << "  --->After creating and allocating memory for nArray." << endl;
    cout << "  nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
    for (int i = 0; i < arraySize; i++)
    {
        nArray[i] = i*i;
    }
    cout << "  --->After initializing nArray." << endl;
    cout << "  nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl << endl;
    for (int i = 0; i < arraySize; i++)
    {
        cout << "  nArray[" << i << "] = " << nArray[i] << " at address <" << nArray + i << ">" << endl;
    }
    cout << endl << "  --->Before reallocating memory for nArray." << endl;
    cout << "  nArray address is <" << nArray << "> and contains the value " << hex << *nArray << endl;
    nArray = new int[arraySize + 2];
    cout << dec << "  --->After reallocating memory for nArray." << endl;
    cout << "  nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
    for (int i = 0; i < arraySize + 2; i++)
    {
        nArray[i] = i*i;
    }
    cout << endl << "  --->After reinitializing nArray." << endl;
    cout << "  nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl << endl;
    for (int i = 0; i < arraySize + 2; i++)
    {
        cout << "  nArray[" << i << "] = " << nArray[i] << " at address <" << nArray + i << ">" << endl;
    }
    cout << endl << "  --->Getting ready to close down the program." << endl;
    cout << "  nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
    // Wait for user input to close program when debugging.
    cin.get();
    return 0;
}

你不能这样做。如果要增加数组的大小,可以创建一个具有所需长度的新数组,并将旧数组的所有内容复制到新数组中,或者您可以简单地使用矢量而不是数组。

C++不能保证它将使用哪个内存,并且您没有删除最初分配的内存,这会导致内存泄漏。