【问题标题】:Ordered Linked List in C causing memory errors?C中的有序链表导致内存错误?
【发布时间】:2015-05-23 08:07:13
【问题描述】:

我写了一个函数

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;
    }
}

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

【问题讨论】:

  • front = copy; 对调用者传入的 front 指针执行 nothing。调用者的指针保持不变。这个问题本质上是相同to this question,可以在本页右侧的列表中找到,尽管有比这更好的解决方法。
  • 欢迎您。 “它没有按预期运行” 到底是什么意思?您是否收到特定的错误消息或类似的信息?如果是,请将其添加到您的问题中。

标签: c memory insert linked-list


【解决方案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 循环将 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);

【讨论】:

  • strcmp((*currentNode)-&gt;next-&gt;name, copy-&gt;name) &lt; 0) { currentnode-> 此处的 next 可能为 NULL ...
  • @joop too:谢谢,复制错误,原始代码在 node_t*-&gt;next 上工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-04
  • 2014-03-26
  • 1970-01-01
  • 2021-12-26
  • 2017-03-14
  • 1970-01-01
相关资源
最近更新 更多