【发布时间】:2021-05-09 19:46:57
【问题描述】:
这里是 C++ 新手。
我的双向链表中有 2 个数据变量; instr_num 和操作码。当我将一个值复制到 instr_num 中时,它可以工作,但是当我为操作码执行此操作时会引发错误。
struct Node {
int instr_num;
std::string opcode;
struct Node* next;
struct Node* prev;
};
void initialize_DLL(Node** tail, Node** head, int s_instr_num, string s_opcode) {
Node* new_node = (Node*) malloc(sizeof(Node));
if (new_node == NULL) {
exit(1);
return;
}
new_node->instr_num = s_instr_num; // THIS EXECUTES
new_node->opcode = s_opcode; // THIS THROWS AN ERROR: free(): invalid pointer
new_node->prev = NULL;
new_node->next = NULL;
*tail = new_node;
*head = new_node;
}
int main(){
Node* tail = NULL;
Node* head = NULL;
std::string temp_opcode = "ADD"
initialize_DLL(&tail, &head, 1, temp_opcode);
return 0;
}
我猜它可能与 malloc 相关,但我不确定。我做错了什么?
【问题讨论】:
-
您分配的
Node中的任何内容都不会被初始化。在 C++ 中使用new。 -
struct int instr_num;这还能编译吗? -
基本上你有未定义的行为,没有人可以仅根据这些信息重现。
-
你为什么使用
malloc?这不是您创建实例的方式。malloc非常特殊,用例非常少见。如果您是初学者,您可能会忘记它存在很长一段时间。我从来不用它 -
@Zoso 我的错。我之前在那里有一个结构,当我发布它时错过了删除它。它只是 int instr_num。
标签: c++ string doubly-linked-list