首页 > 解决方案 > 在节点生成中取消引用 NULL 指针警告

问题描述

VS 2019 已将以下c 代码标记为 c6011 警告。该函数假设为我的双向链表“客户端”初始化一个空节点。初始化新节点时我做错了什么吗?

//struct for my doubly linked list
typedef struct _client {
    char NAME[30];
    unsigned long PHONE;
    unsigned long ID;
    unsigned char CountryID;
    struct client *next;
    struct client *previous;
}client, *client_t;

//Function which creates a new node and returns a ptr to the node
client_t AddClientNode() 
{
    client_t ptr = (client_t)malloc(sizeof(client));
    //Warning C6011 Dereferencing NULL pointer 'ptr'. 
    ptr->next = NULL; 
    ptr->previous = NULL;
    return ptr;
}

标签: cwarnings

解决方案


退休忍者的建议适用于我的代码。ptr 需要检查以确保它不是由于 malloc 失败而导致的空值。以下代码是没有警告的工作功能:

client_t AddClientNode() {
    client_t ptr = malloc(sizeof(client));
    if (ptr)
    {
        ptr->next = NULL;
        ptr->previous = NULL;
        return ptr;
    }
    else printf("Malloc Failed to Allocate Memory");
    return NULL;
}

推荐阅读