使用malloc的C中的分段错误

使用malloc的C中的分段错误

本文介绍了使用malloc的C中的分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下情况下,我遇到了细分错误: 从文件中读取IP地址列表时,我将IP地址和端口存储在链接列表中. 根据链接列表逻辑,当我的while循环用于文件读取时,它本身会重复-当我再次分配临时指针时,我会遇到分段错误.

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. 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.

请在下面的代码段中找到

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;
                    }
              }
         }
  }

文件格式为:

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

worker1=10.10.10.1worker2=10.10.10.2(both worker1 and worker2 in different lines.)

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

While reading worker1 there is no problem in the execution. However, when the file is at line 2 - worker2, the code gives segmentation fault during malloc of string.
Can you please help me with this.

推荐答案

strcpy(temp->ip_Address, ch);

u应该在strcpy之前先分配temp-> ip_address

u should malloc temp->ip_address before strcpy

这篇关于使用malloc的C中的分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:30