c - 在节点生成中取消引用 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;
}
解决方案
退休忍者的建议适用于我的代码。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;
}
推荐阅读
- apache - Apache重定向覆盖不一致
- javascript - 运行 ng build --prod 时,类型“{}”上不存在属性“title”,但可以与 ng serve 一起使用
- python - 编写一个对文件中一行中的字符串进行计数的程序时遇到问题
- angular - 我们应该在哪里取消订阅 Angular 的 SwUpdate.available?
- javascript - 过滤不区分大小写
- php - 为什么我的由简码返回的 html 没有作为 html 执行?
- c - 如何从链表的特定节点中删除和清除内存?
- cassandra - Cassandra 集群密钥顺序
- android - 无需插入即可在设备上本地运行 Ionic Android App
- java - 我无法编辑日期和时间