gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:55:55 24 4
gpt4 key购买 nike

我正在尝试在 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/

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