首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何检测内存是否已分配?(链表)

如何检测内存是否已分配?(链表)
EN

Stack Overflow用户
提问于 2017-10-24 05:09:59
回答 2查看 54关注 0票数 2

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

问题是,我如何知道内存是否已成功分配,或元素是否已成功添加?代码如下:

代码语言:javascript
复制
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;
}
EN

Stack Overflow用户

发布于 2017-10-24 05:50:02

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

原型应更改为

代码语言:javascript
复制
int push_back(pos_t **headp, int new_value);

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

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

下面是相应的代码:

代码语言:javascript
复制
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;
}
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46898600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档