Home  >  Q&A  >  body text

A malloc problem in c++ linked list

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.

習慣沉默習慣沉默2657 days ago768

reply all(1)I'll reply

  • typecho

    typecho2017-06-14 10:53:40

    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.

    reply
    0
  • Cancelreply