在双向链表中分配多个变量时如何解决 free(): invalid pointer 错误?

How to resolve free(): invalid pointer error while assigning multiple variables in a doubly linked list?

这里是 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 做些什么,但我不确定。我做错了什么?

在 C++ 中,您将使用 new 来初始化分配的内存:

#include <string>
#include <utility>

struct Node {
  int instr_num;
  std::string opcode;
  Node* next;
  Node* prev;
};

void initialize_DLL(Node** tail, Node** head, int s_instr_num,
                    std::string s_opcode) {
  *tail = *head =
      new Node{s_instr_num, std::move(s_opcode)};  // NULLs are implicit
}

int main() {
  Node* tail = NULL;
  Node* head = NULL;
  std::string temp_opcode = "ADD";

  initialize_DLL(&tail, &head, 1, temp_opcode);

  delete tail;  // don't leak
}

请注意,使用原始指针很危险。

在 C 中,您将使用 flexible array member:

#include <stdlib.h>
#include <string.h>

struct Node {
  int instr_num;
  struct Node* next;
  struct Node* prev;
  char opcode[];
};

void initialize_DLL(struct Node** tail, struct Node** head, int s_instr_num,
                    char const* s_opcode) {
  size_t str_sz = strlen(s_opcode) + 1;
  *tail = *head = malloc(sizeof(struct Node) + str_sz);

  if (!*head)
    return;

  (*head)->instr_num = s_instr_num;
  (*head)->next = NULL;
  (*head)->prev = NULL;
  memcpy((*head)->opcode, s_opcode, str_sz);
}

int main() {
  struct Node* tail = NULL;
  struct Node* head = NULL;
  char const* temp_opcode = "ADD";

  initialize_DLL(&tail, &head, 1, temp_opcode);

  free(head);
}

C++ 中不存在“灵活数组成员”的概念。您可以使用 1 个字符的数组来模拟类似的东西,但根据 C++ 标准,索引其他字符将是未定义的行为。所以,不要在 C++ 中使用它,除非你的编译器明确允许并且你可以使用不可移植的代码。