对于以下情况,我遇到了分段错误:从文件中读取 IP 地址列表时,我将 IP 地址和端口存储在链接列表中。当我的文件读取的while循环重复时,根据链接列表逻辑 - 当我再次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<=nbrwrk )
{
ch = strtok(line,"=");
while (ch != NULL)
{
if (strstr(ch,"worker") ! = NULL)
{
// temp = NULL;-> 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 期间出现分段错误。
你能帮我解决这个问题吗?