简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM