简体   繁体   中英

Dereferencing NULL pointer warning in node generation

VS 2019 has tagged the following c code with a c6011 warning. The function is suppose to initialize an empty node for my doubly linked list "Client". Am I doing something wrong when initializing a new node?

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

Retired Ninja's suggestion worked for my code. The ptr needed a check to make sure it wasn't null from malloc failing. The below code is the working function without the warning:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM