C中的有序链接列表导致内存错误?

时间:2015-05-23 08:07:13

标签: c memory insert linked-list

我写了一个函数

void
insertNode(node_t *front, node_t *nodeIn) {
    node_t *currentNode = front;
    node_t *copy;
    if (!(copy = (node_t*)malloc(sizeof(struct node)))) {
        printf("Out of memory, exiting here?");
        exit(0);
    }   
    strcpy(copy->name, nodeIn->name);
    copy->aisle = nodeIn->aisle;
    copy->shelf = nodeIn->shelf;
    copy->mass = nodeIn->mass;
    copy->price = nodeIn->price;
    copy->quantity = nodeIn->quantity;
    copy->next = NULL;

    if (front == NULL || strcmp(front->name,copy->name) > 0) {
        copy->next = currentNode;
        front = copy;
        printf("%s\n", front->name);
    }
    else {  
        while (currentNode->next != NULL && 
            strcmp((currentNode->next)->name,copy->name) < 0) {
            currentNode = currentNode->next;
        }
        copy->next = currentNode->next;
        currentNode->next = copy;
    }
}

它接收指向前节点和我想要插入列表的节点的指针,但它没有按预期运行。我的代码中有没有明显的点可能会破坏?

1 个答案:

答案 0 :(得分:1)

/**
 * @param front Might be changed upon insertion in front
 * @param nodeIn payload to insert; will neither be changed,
 *               nor used in the list
 */
void
insertNode(node_t **front, node_t *nodeIn) {
    node_t *copy;
    if (!(copy = (node_t*)malloc(sizeof(node_t)))) {
        printf("Out of memory, exiting here?");
        exit(0);
    }   
    copy->name = strdup(nodeIn->name);
    copy->aisle = nodeIn->aisle;
    copy->shelf = nodeIn->shelf;
    copy->mass = nodeIn->mass;
    copy->price = nodeIn->price;
    copy->quantity = nodeIn->quantity;

    node_t **currentNode = front;
    while (*currentNode != NULL && strcmp((*currentNode)->name, copy->name) < 0) {
        currentNode = &(*currentNode)->next;
    }
    copy->next = *currentNode;
    *currentNode = copy;
}
  • front指针是一个输入输出参数,因为在前面插入时可能会更改。
  • name未分配,strdup使字符串重复。
  • currentNode是别名。它允许更改前变量或下一个字段。
  • wile-loop将currentNode定位在右侧变量上。

删除也应该是免费名称。

用法:

node_t *list = NULL;
node_t data;

data.name = "unu";
...
insertNode(&list, &data);
data.name = "du";
...
insertNode(&list, &data);
data.name = "tri";
...
insertNode(&list, &data);