Does calling new [] twice on the same pointer without calling delete [] in between cause a memory leak?

后端 未结 6 1015
天命终不由人
天命终不由人 2021-01-25 19:21

I\'ve heard that you should usually \"delete\" whenever you use \"new\", yet when I run a simple test program (below), it doesn\'t seem to make a difference which numbers I put

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-25 20:03

    Two questions, two answers.

    Question one: Does calling new [] twice on the same pointer without calling delete [] in between cause a memory leak?

    Answer one: Not always, but 99% of the time yes. The code below calls new twice, with the pointer to array, but the first time it assigns the address of the allocated memory to array2, and the second time it keeps the address to itself. It is possible to delete both array in this scenario.

    #include 
    
    int main()
    {
        double *array;
        double *array2;
        const int arraySize = 100000;
    
        for (int i = 0; i < 2; i++)
        {
            // do I need to call "delete [] array;" here?
            array = new double[arraySize];
            if(i == 0)
            {
                array2 = array;
            }
        }
    
        int x;
        std::cin >> x; // pause the program to view memory consumption
    
        delete [] array;
        delete [] array2;
    
        return 0;
    }
    

    Question Two: Is this usage of delete [] sufficient?

    Answer Two: no, because the delete call only influences the address pointed to by the pointer you've given it. As you overwrote the pointer in your example, it deletes the last allocated section of memory

提交回复
热议问题