我正在開發一個客戶端 - 服務器程序,當我試圖用這個結構來實現用戶鏈接列表:內存分配碼錯誤
typedef struct user {
char username[50];
int user_pid;
struct user *next;
} user_list;
我試圖找出什麼是錯的代碼,因爲編譯器不會給我任何錯誤,但是當我嘗試用戶打印用戶列表時,它根本不顯示任何內容。
ADDUSER功能:
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++;
}
主要功能(精簡版)
int Main()
{
struct request req;
struct answer ans;
user_list *head = NULL;
do{
read(fifo_1, &req, sizeof(req)); // Read client request
if(strcasecmp(req.str, "adduser") == 0)
{
AddUser(head, req);
strcpy(ans.str, "User added with success! You're logged!");
}
if(strcasecmp(req.str, "users") == 0) // Print on the screen the users list
{
user_list *current = head;
while (current != NULL)
{
fprintf(stdout, "%s\n", current->username);
fprintf(stdout, "%d\n", current->user_pid);
current = current->next;
}
}
}while(strcmp(req.str,"exit") != 0);
}
@pzaenger我不好,我寫這部分只是在這裏顯示出來,我忘了。我已經編輯了這篇文章。 – 2014-09-05 17:54:04
「主」功能的變量'head'在AddUser中沒有更新。您需要傳遞對指針或指針的指針的引用,以便能夠在內部進行更新並反映到外部。使用這個:'void AddUser(user_list *&head,req req)'或'void void AddUser(user_list ** head,req req)' – NetVipeC 2014-09-05 17:54:39
'int Main()'不是傳統C(C區分大小寫,它是'int main()')。請查看如何創建一個MCVE([最小,完整,可驗證示例](http://stackoverflow.com/help/mcve))或 SSCCE([Short,Self-Contained,Correct Example](http:// sscce .org /)) - 兩個名稱和鏈接的基本概念相同。它將爲您提供比不可編譯的代碼更好的幫助。你需要錯誤的檢查'read()'調用。 – 2014-09-05 17:54:59