【问题标题】:How to detect if memory was allocated? (Linked lists)如何检测是否分配了内存? (链接列表)
【发布时间】:2018-04-04 13:07:48
【问题描述】:

我想创建一个将元素添加到链表末尾的函数。如果元素添加成功,它还必须返回 0,如果无法为元素分配/保存内存,则返回 1。

问题是,如何知道内存分配成功还是元素添加成功?这是代码:

int push_back(pos_t *head, int new_value) {
    pos_t *temp = head;

    while (temp->next != NULL) {
        temp = temp->next;
    }
    pos_t *temp1 = (pos_t *)malloc(sizeof(pos_t));
    temp1->data = new_value;
    temp1->next = NULL;
    temp = temp1;
}

【问题讨论】:

  • temp=temp1; --> temp->next = temp1; ?
  • head == NULL 可能吗?看看链接列表是如何初始化的会很有用。

标签: c memory linked-list malloc


【解决方案1】:

需要添加以下代码

if (temp1 == NULL) { return 1; }

因为malloc 被定义为要么返回一个指向已分配内存的指针,要么

  • 如果大小为零,则返回 NULL。
  • 出错时,返回 NULL。

您可以控制不请求大小为零,因此如果您使用正大小,并且malloc 返回 NULL,则可以推断发生了错误。

许多系统都安装了“手册”。如果您使用的是 Linux 系统,命令“man malloc”将打开malloc 的手册页。如果您使用的是 Windows 系统,则在网络上搜索 the manual for malloc 将为您提供足够的详细信息来处理详细信息。

【讨论】:

  • 当然,您还需要添加return 0;,两个代码添加的位置留给您自己弄清楚。
【解决方案2】:

该函数有一个缺点:不能用于分配列表中的第一个节点,即如果列表为空。

原型应该改成

int push_back(pos_t **headp, int new_value);

传递列表指针的地址而不是其值。

测试malloc() 失败很简单:将返回的指针与NULL0 进行比较。

下面是对应的代码:

int push_back(pos_t **headp, int new_value) {
    pos_t *temp = *headp;
    pos_t *temp1 = malloc(sizeof(pos_t));
    if (temp1 == NULL) {   // allocation failure
        return 1;
    }
    temp1->data = new_value;
    temp1->next = NULL;

    if (temp == NULL) {      // empty list
        *headp = temp1;
    } else {
        while (temp->next != NULL) {
            temp = temp->next;
        }
        temp->next = temp1;  // append node to the end of the list
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 2011-04-06
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多