>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;
}
退休忍者的建议适用于我的代码。ptr 需要进行检查,以确保它不会因 malloc 失败而为空。下面的代码是不带警告的工作函数:
client_t AddClientNode() {
client_t ptr = malloc(sizeof *ptr);
if (ptr)
{
ptr->next = NULL;
ptr->previous = NULL;
return ptr;
}
fprintf(stderr, "Malloc Failed to Allocate Memoryn");
return NULL;
}