How to Delete New Memory in Vector

Look at my error sample code:

std::vector<CObject*> ObjectSet = std::vector<CObject*>(3000);
CObject* pDataSet = new CObject[3000]();//To avoid memory fragmentation, allocate continuous memory first.
for (unsigned int i=0; i<ObjectSet.size(); ++i)
    {
        ObjectSet[i] = pDataSet + i;
        //ObjectSet[i] = & pDataSet[i]; //The effect is equivalent to the previous line. 
    }
//Freeing Memory
    for (unsigned int i=0; i<ObjectSet.size(); ++i)
    {
        delete ObjectSet[i];
    }

The result is a runtime error. Pointer in delete second Vector is wrong:

does not understand the mechanism of dynamic memory allocation and release. This is a runtime error.
example above, dynamic memory request, but free 3000 times!!!! No wonder you report an error.
“CObject* pDataSet = New CObject[3000] ();” The bottom line is this: allocate 3000 * sizeof(CObject) size memory from the heap and call CObject’s constructor 3000 times to initialize the allocated dynamic memory. Note: When allocating memory, the associated dynamic storage management data structure (free linked lists or bitmaps) records the first address and size of the dynamic memory you requested. Moreover, this memory can only be released once! Because the data structure records such a first address and size. When freed, memory of a specified size in the data structure is continuously returned to free storage, starting at the first address, and then the destructor is called.
The difference between DELETE and DELETE [] : If you create an array of objects dynamically, delete can only call the destructor on the 0th object element of the data, and no other object elements can be called. Delete [] calls the destructor on all object elements in the array. If an object in an array is also dynamically created when its members are created, using DELETE is bound to leak memory.
Delete ObjectSet[I]; Repeated execution, multiple release of dynamic memory, the second loop, inevitable error.
You can’t just read programming books, operating systems, and data structures if you want to get ahead. That’s what dynamic storage management in operating systems is all about.
Memory leaks:
_CrtDumpMemoryLeaks(); // detect memory leak
//_CrtSetBreakAlloc(173); // Locate memory leaks


Read More: