[英]Segmentation fault in C with malloc
I'm getting a segmentation fault for the below scenario: When reading from a file for a list of ip addresses, i store the IP ADDRESS and port in a link list. 在以下情况下出现分段错误:从文件中读取IP地址列表时,我将IP地址和端口存储在链接列表中。 As my while loops for file reading repeats itself, as per link list logic - when i malloc my temp pointer again i face segmentation fault.
根据链接列表逻辑,当我的while循环用于文件读取时,它本身会重复-当我再次分配临时指针时,我遇到了段错误。
Please find below the code snippet: 请在下面的代码段中找到:
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;
}
}
}
}
File format is : 文件格式为:
worker1=10.10.10.1 worker2=10.10.10.2 (both worker1 and worker2 in different lines.) worker1 = 10.10.10.1 worker2 = 10.10.10.2(worker1和worker2在不同的行中。)
While reading worker1 there is no problem in the execution. 在读取worker1时,执行没有问题。 However, when the file is at line 2 - worker2, the code gives segmentation fault during malloc of string.
但是,当文件位于第2行-worker2时,代码在字符串malloc期间给出了分段错误。
Can you please help me with this. 你能帮我这个忙吗?
strcpy(temp->ip_Address, ch);
你应该在strcpy之前malloc temp-> ip_address
Change this: 更改此:
if (head = NULL)
to 至
if (head == NULL)
==
operator checks for equality between two expressions. ==
运算符检查两个表达式之间的相等性。
=
is an assignment operator. =
是赋值运算符。 It assigns the value at/of RHS to variable at LHS. 它将RHS处的值分配给LHS处的变量。
Also, as ouaacss suggested, either allocate memory for ip_address
or declare it as a character array. 另外,正如ouaacss所建议的,要么为
ip_address
分配内存,要么将其声明为字符数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.