内存分配代码错误

时间:2014-09-05 17:47:53

标签: c linux xubuntu

我正在开发一个客户端 - 服务器程序,当我和我正在尝试使用此结构实现用户链接列表时:

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

1 个答案:

答案 0 :(得分:1)

将其他人已经在评论中指出的内容放在一起:

  1. 更改main。而不是

    int Main()
    

    使用

    int main()
    
  2. head中更改main时,AddUser的值不会发生变化。这是一个解决方案。从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;
    }
    
  3. AddUser中捕获main的返回值。而不仅仅是

    AddUser(head, req);
    

    使用

    head = AddUser(head, req);