C 内存分配代码错误
我正在开发一个客户机-服务器程序,并尝试使用以下结构实现用户链接列表:C 内存分配代码错误,c,linux,xubuntu,C,Linux,Xubuntu,我正在开发一个客户机-服务器程序,并尝试使用以下结构实现用户链接列表: typedef struct user { char username[50]; int user_pid; struct user *next; } user_list; 我试图找出代码的错误,因为编译器没有给我任何错误,但是当我尝试使用户打印用户列表时,它根本没有显示任何内容 添加用户功能: AddUser(user_list *head, req req) { if(head == N
typedef struct user {
char username[50];
int user_pid;
struct user *next;
} user_list;
我试图找出代码的错误,因为编译器没有给我任何错误,但是当我尝试使用户打印用户列表时,它根本没有显示任何内容
添加用户功能:
AddUser(user_list *head, req req)
{
if(head == NULL)
{
head = malloc(sizeof(user_list));
if (head == NULL)
fprintf(stdout,"[SERVER] Error memory allocation ");
strcpy(head->username, req.str);
head->user_pid = req.client_pid;
head->next = NULL;
}
else
{
user_list *current = head;
while (current->next != NULL)
current = current->next;
current->next = malloc(sizeof(user_list));
strcpy(current->next->username, req.str);
current->next->user_pid = req.client_pid;
current->next->next = NULL;
}
num_users++;
}
主功能(短版)
综合其他人在评论中已经指出的内容:
main
。而不是
int Main()
使用
AddUser
中更改head
的值时,它在main
中不会更改。这里有一个解决方案。从AddUser返回head
user_list* AddUser(user_list *head, req req)
{
if(head == NULL)
{
head = malloc(sizeof(user_list));
if (head == NULL)
fprintf(stdout,"[SERVER] Error memory allocation ");
strcpy(head->username, req.str);
head->user_pid = req.client_pid;
head->next = NULL;
}
else
{
user_list *current = head;
while (current->next != NULL)
current = current->next;
current->next = malloc(sizeof(user_list));
strcpy(current->next->username, req.str);
current->next->user_pid = req.client_pid;
current->next->next = NULL;
}
num_users++;
return head;
}
main
中捕获AddUser
的返回值。而不仅仅是
AddUser(head, req);
使用
@我的错,我写这部分只是为了在这里展示,我忘了。我已经编辑了帖子。
main
函数的变量head
在AddUser中没有更新。您需要传递对指针的引用或指向指针的指针,以便能够在内部更新并在外部反映。使用此选项:void AddUser(user\u list*&head,req)
或void AddUser(user\u list**head,req)
int Main()
也不是传统的C(C区分大小写,是int Main()
)。请回顾如何创建一个MCVE()或SSCCE()——两个名称和相同基本思想的链接。与不可编译的代码相比,它将为您提供更好的帮助。您需要对read()
调用进行错误检查。@JonathanLeffler,正如我在下面所说的,我只是把代码中与链表相关的最重要部分放在这里。也许我有一些错误,但是我的代码运行得很好,除了这一部分(内存分配)。但我会听从你的建议!谢谢。我们不能调试我们看不到的东西——尽管我认为NetVipeC可能已经解决了真正的问题。当您寻求帮助时,请礼貌地询问显示的代码在哪里编译(当然,除非整个问题是它没有编译,但应该编译),最好代码应该完整,以便我们可以自己编译(应该简短,并且应该在您的系统上重现问题)。是的,在可复制和最小复制之间存在相互冲突的目标,但是在最小复制上工作通常可以帮助您解决问题。它工作得非常完美!谢谢,很抱歉我是一个初学者,SSCE概念对我来说是一个新概念。@MarcodeBarbosa,不客气。没有必要为自己是初学者而道歉。我们都从那里开始。生活和学习:)
user_list* AddUser(user_list *head, req req)
{
if(head == NULL)
{
head = malloc(sizeof(user_list));
if (head == NULL)
fprintf(stdout,"[SERVER] Error memory allocation ");
strcpy(head->username, req.str);
head->user_pid = req.client_pid;
head->next = NULL;
}
else
{
user_list *current = head;
while (current->next != NULL)
current = current->next;
current->next = malloc(sizeof(user_list));
strcpy(current->next->username, req.str);
current->next->user_pid = req.client_pid;
current->next->next = NULL;
}
num_users++;
return head;
}
AddUser(head, req);
head = AddUser(head, req);