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

后端 未结 6 1084
天命终不由人
天命终不由人 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 19:53

    Yes. Fortunately, there's a better way -- instead of allocating the memory directly, use std::vector:

    #include 
    #include 
    
    int main()
    {
        double *array;
        const int arraySize = 100000;
        const int numLoops = 100000;
    
        for (int i = 0; i < numLoops; i++)
        {
           std::vector array(arraySize);
           // use it just like a normal array
        }
    
        int x;
        std::cin >> x; // pause the program to view memory consumption
        return 0;
    }
    

    The vector will be destroyed (and the memory it controls released) each iteration of the loop.

    You shouldn't generally use new unless you really need to. I'd go so far as to say there's never a need (or even good reason) to use the array form of new.

提交回复
热议问题