C语言中带malloc的分段错误
我在下面的场景中遇到了一个分段错误: 从文件中读取ip地址列表时,我将ip地址和端口存储在链接列表中。 由于文件读取的while循环重复自身,按照链接列表逻辑-当我再次malloc临时指针时,我面临分段错误 请在下面找到代码片段:C语言中带malloc的分段错误,c,list,segmentation-fault,malloc,C,List,Segmentation Fault,Malloc,我在下面的场景中遇到了一个分段错误: 从文件中读取ip地址列表时,我将ip地址和端口存储在链接列表中。 由于文件读取的while循环重复自身,按照链接列表逻辑-当我再次malloc临时指针时,我面临分段错误 请在下面找到代码片段: struct woker_conf { int port; char *ip_address; struct worker_conf *next; } *he
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;
}
}
}
}
struct woker\u conf
{
国际港口;
字符*ip_地址;
结构工作者配置*下一步;
}*团长;
无效打开(int8_t nbrwrk)
{
FILE*fp=NULL;
字符行[1024]={0};
int i=1;
char*ch;
结构工作者配置*config,*temp;
head=NULL;
fp=fopen(“abcd.txt”,“r”);
如果(fp==NULL)
出口(1);
while(fgets(line,sizeof line,fp)!=NULL&&i有或没有此行的分段错误
temp=(结构工作者配置*)malloc(sizeof(结构工作者配置));
ch=strtok(空,“”);
strcpy(临时->ip地址,ch);
if(head==NULL)
{头=温度;
head->next=NULL;
}
配置=(结构工作者配置*)头;
while(配置->下一步!=NULL)
config=config->next;
配置->下一步=温度;
配置=温度;
config->next=NULL;
}
}
}
}
文件格式为:
工人1=10.10.10.1
工人2=10.10.10.2
(worker1和worker2位于不同的行中。)
读取worker1时,执行过程中没有问题。但是,当文件位于第2行-worker2时,代码在字符串malloc期间给出分段错误。你能帮我解决这个问题吗。改变这个:
if(head=NULL)
到
if(head==NULL)
=
运算符检查两个表达式之间是否相等。=
是一个赋值运算符。它将RHS/处的值赋值给LHS处的变量
此外,正如ouaacss所建议的,为ip\u地址
分配内存或将其声明为字符数组
strcpy(temp->ip_Address, ch);
如果(head=NULL),你应该在strcpy之前使用malloc temp->ip\u地址
if(head=NULL)
应该是if(head==NULL)
或者if(!head)
。谢谢..事实上这是一个输入错误。很抱歉。谢谢。它解决了我的问题。只是为了学习观点->你能解释一下,在没有malloc to temp->ip\u地址的情况下,可执行文件是如何运行的吗?在没有malloc temp->ip\u地址的情况下,将内存分配给我们面前的对象指针temp时,这导致了分段错误如果指针指向无效地址,这将导致严重的内存问题。在mac上,它将引发EXC_BAD_address异常,而在linux上,我认为它只会修改一些你不知道的地址,并导致系统坏运气。。。