C++ vector insert dynamic memory (new, malloc requested memory) and destroy dynamic memory (delete, free)demo

When we use a vector, we sometimes insert dynamic memory data (such as a pointer from new into the vector). At this time we must pay attention to C++ memory management, because C++ memory management principle, who apply, who destroy. If we clear() without destroying the dynamic memory of the pointer in the vector, we will cause a memory leak. Therefore, we need to first traverse the vector, destroy the dynamic memory corresponding to the elements stored in the vector, and then clear() the vector.

The demo sample:

#include <vector>
#include <iostream>
#include <cstring>
using namespace std;
 
int main(a)
{
    vector<char *> obj;
    
    // Insert dynamic memory into vector
    for(int i=0; i<10; i++) {char * ptr = new char[100];
        memset(ptr, 0 , 100);
        
        obj.push_back(ptr);
    }

    // The requested dynamic memory must be cleaned before the vector can be emptied; otherwise, memory leaks will occur
    for(vector<char *>::iterator it = obj.begin(a); it ! = obj.end(a); it++) {if(*it ! =NULL)
        {
            delete *it;
            *it = NULL;
        }
    }
    obj.clear(a);return 0;
}
Copy the code

New char[100] = new char(100) = new char(100

New char(100) new char(100) It’s wrong… Ah… So I added a sidebar, for the record. New char[100] = new char(100) = new char(100) = new char(100) = new char(100) Details are as follows:

char *p = new char[200]; // new a char array of size 200
char *p = new char(200); //new a char with an initial value of 200
Copy the code

The end of the message

That concludes the small details of vector. I’ll see you in the next post

It is not easy to write a blog, such as being loved, appreciate a concern, one key three connect ~~ like + comment + collection 🤞🤞🤞, thank you for your support ~~Copy the code