在节点生成中取消引用NULL指针警告

问题描述 投票:0回答:1

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

//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;
}
c warnings
1个回答
0
投票

退休的忍者的建议适用于我的代码。 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;
}
© www.soinside.com 2019 - 2024. All rights reserved.