Segmentation fault in C with malloc

老子叫甜甜 提交于 2019-12-13 04:46:29

问题


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

File format is :

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

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.


回答1:


strcpy(temp->ip_Address, ch);

u should malloc temp->ip_address before strcpy




回答2:


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.

Also, as ouaacss suggested, either allocate memory for ip_address or declare it as a character array.



来源:https://stackoverflow.com/questions/19970096/segmentation-fault-in-c-with-malloc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!