gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:18:30 26 4
gpt4 key购买 nike

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

最佳答案

退休忍者的建议适用于我的代码。 ptr 需要检查以确保它不会因 malloc 失败而为 null。下面的代码是没有警告的工作函数:

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 Memory\n");
return NULL;
}

关于c - 节点生成中取消引用 NULL 指针警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55885461/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com