C中的分段错误与malloc

我在下面的场景中遇到了分段错误:当从文件中读取ip地址列表时,我将IP ADDRESS和端口存储在链接列表中。 因为我的文件读取循环重复自己,按照链接列表逻辑 – 当我再次malloc我的临时指针时,我面临分段错误。

请在下面找到代码段:

struct woker_conf { int port; char *ip_address; struct worker_conf *next; } *head; void open(int8_t nbrwrk) { FILE *fp = NULL; char line[1024] = {0}; int i = 1; char *ch; struct worker_conf *config, *temp; head = NULL; fp = fopen("abcd.txt","r"); if (fp == NULL) exit(1); while (fgets(line, sizeof line, fp) != NULL && i segmentation fault with and without this line temp = (struct worker_conf *)malloc(sizeof(struct worker_conf)); ch = strtok(NULL," "); strcpy(temp->ip_Address, ch); if (head == NULL) { head = temp; head->next = NULL; } config = (struct worker_conf *)head; while (config->next != NULL) config = config->next; config->next = temp; config = temp; config->next = NULL; } } } } 

文件格式为:

worker1 = 10.10.10.1 worker2 = 10.10.10.2(不同行中的worker1和worker2。)

在读取worker1时,执行中没有问题。 但是,当文件位于第2行 – worker2时,代码在malloc的字符串期间给出了分段错误。
你能帮我解决这个问题吗?

 strcpy(temp->ip_Address, ch); 

你应该在strcpy之前使用malloc temp-> ip_address

改变这个:

if (head = NULL)

if (head == NULL)

==运算符检查两个表达式之间的相等性。
=是赋值运算符。 它将RHS的值分配给LHS的变量。

另外,正如ouaacss建议的那样,要么为ip_address分配内存,要么将其声明为字符数组。