C++ C++;纠正内存泄漏

C++ C++;纠正内存泄漏,c++,C++,有人能帮我找出如何重用分配的内存吗?这段代码的最终结果应该是在第一次和第二次数组初始化时使用相同的位置。数组化是常数5 编辑:我想出来了。我只需要使用免费的(nArray);就在“nArray=newint[arraySize+2];”行之前,这允许我更正泄漏并重用相同的内存位置 int main() { cout << endl << endl; int* nArray = new int[arraySize]; cout << "

有人能帮我找出如何重用分配的内存吗?这段代码的最终结果应该是在第一次和第二次数组初始化时使用相同的位置。数组化是常数5

编辑:我想出来了。我只需要使用免费的(nArray);就在“nArray=newint[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;
}
intmain()
{

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


C++不能保证你使用的内存,你没有删除你最初分配的内存,它会导致内存泄漏。

C++标准没有保证你“重用”。内存,不管怎样。如果你需要重用特定的内存块,你必须为你的自定义容器编写自己的低级分配器。这是一个明显的XY问题。你试图解决的真正问题是什么。不,不是关于使用同一内存位置的问题,而是你认为解决方案要解决的任何问题相同的内存位置。尝试使用向量来管理数组,然后使用调整大小。关于编辑:这绝对不能保证。仅仅因为你
空闲
那里有什么并不意味着空间将被下一个
新建
使用(你为什么混合使用malloc/free和new/delete?)你的代码没有任何使用
delete[]
的迹象。因此出现漏洞。如果你在
new
分配的内存上使用
free
,即UB。使用
free
将是错误的。此外,请不要在问题中编辑答案。答案应张贴在答案框中。然后人们可以对其进行评论和投票。