A malloc problem in c++ linked list
習慣沉默
習慣沉默 2017-06-14 10:51:40
0
1
796

I defined a structure as follows:

typedef struct CommandNode {
    int type;
    vector<string> command;
    CommandNode *next;
} CommandList,*CommandListNodes;

There is a vector in this structure, and now I want to use it as a linked list. I am not sure how to malloc the vector.

I used to malloc a 1000, and sometimes the following problems would occur:

malloc: *** error for object 0xffbbe8909090ffff: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

In addition, I don’t know if it can be used like this:

    CommandListNodes listNodes = new CommandList;
    CommandListNodes p = listNodes;
    
    p->command.push_back("121212");
    
    p->type=100;
    p->next=new CommandList;
    
    p = p->next;
    
    p->command.push_back("343434");
    
    p->type=200;
    p->next=new CommandList;
    
    p = p->next;

And what is the difference between it and malloc? Currently, my understanding of this part of knowledge is relatively confusing. I haven’t found any particularly suitable content on the Internet. I hope some friends can sort it out. Thank you.

習慣沉默
習慣沉默

reply all(1)
typecho

Always remember that dynamic memory allocation in C++ is related to pointers. For example, to access the content pointed by an int pointer, its memory must be allocated. This means that if a pointer is not initialized using & (address) or assignment, then it must be initialized using dynamic memory allocation methods such as new or malloc to ensure that the memory pointed to by the pointer exists. For vectors, you can either use vector<T> name to declare a vector, or you can use vector<T> * p = new vector<T> to declare and define a pointer to the vector.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!