c - 在C中的链表的末尾或开头添加节点

标签 c linked-list

我正在尝试在 Linux 中使用命名管道创建服务器/客户端程序。 每次客户端连接和验证时,服务器都会将其数据(pid 和密码)存储在链表中。

问题是,在我存储第一个客户端的数据后,每当我尝试存储更多数据(客户端)时,程序“给出”段错误

typedef struct client client, *pno;
struct client
{
    pid_t pid;
    char password[TAM_MAX];
    pno next;   
};

int verify_struct(pno cliente_t)
{
    if (cliente_t == NULL) //verifica se a lista está vazia
        return 1;
    else
        return 0;
}

    pno AddClient(pno cliente_t, pid_t pid, char password[TAM_MAX]) 
    {
        pno new, aux;
        new = malloc(sizeof(client)); //aloca espaço

        if(new == NULL) //verifica se alocou o espaço com sucesso
            {
                printf("Memory allocation error!\n");
                return cliente_t;
            }

        new->pid = pid;
        strncpy(new->password, password, TAM_MAX-1);

        if(verify_struct(cliente_t))
            {
                printf("Should be at start\n");
                cliente_t = new;
                printf("Added at start!\n");
            }
        else
            {
                //insert at end
                printf("Adding in the end!\n");
                aux = cliente_t;
                while(aux->next != NULL)
                    aux = aux->next;
                aux->next = new;
                printf("Added sucssefully!\n");
            }
        return cliente_t;
    }

bool isValidUser(pno cliente,  pid_t pid, char password[TAM_MAX])
{
    while(cliente != NULL)
        {
            if(cliente->pid == pid && strncmp(password, cliente->password, 100) == 0)
                {
                    return true;
                }
            cliente = cliente -> proximo;
        }
        return false;
}

    //progam itself :

int main(void)
{
    pno client=NULL;

    /* --code-- */

    while(1)
        {
                if(request.loggedIn == 0)
                    {
                        client=AddClient(client, request.pid, request.password);
                    }
                else
                    {
                        if(!isValidUser(cliente, perg.pid_cliente, perg.password))
                            abort();
                        //process commands
                    }
        }

}

输出:

1st Client -> Should be at start!
           -> Added at start!

2nd Client -> Adding in the end!
           -> segmentation fault (core dumped).

最佳答案

您需要将此行添加到 AddClient

new->next = NULL;

否则 new->next 包含未初始化的内存。稍后当您检查 aux->next != NULL(aux 现在等于之前的 new )时,测试不会评估为真,因为未初始化的内存不会碰巧等于 0。然后您试图找到未初始化内存中的值指向的另一个节点。它可能包含实际上不是合法内存地址的数据,因此是段错误。

关于c - 在C中的链表的末尾或开头添加节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17056060/

相关文章:

c - C中的合并链表

java - 堆栈、括号匹配

c - libjit 是否动态地将一段代码转换为可执行文件?

c - 为什么 vsnwprintf 不见了

c - c程序中包含的头文件的默认路径是什么?

java - 我无法弄清楚这个 ConcurrentModificationException

java - Java 中的节点,来自 C 背景

c - 为什么在我第一次在代码中插入项目后,我的代码中出现段错误

c - ffmpeg/libavfilter 中的字幕

c++ - 一个简单的 getch() 和 strcmp 问题