VS 2019已使用c6011警告标记以下 c代码。该函数假定为我的双向链接列表“客户端”初始化一个空节点。初始化新节点时我做错什么了吗?
//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;
}
答案 0 :(得分:0)
退休忍者的建议适用于我的代码。 ptr需要检查以确保它不会因malloc失败而为null。以下代码是没有警告的工作功能:
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;
}