简体   繁体   中英

strtok() giving segmentation fault in C

I'm trying to parse a string that is separated by semicolons. The first 3 tokens are ints and the last token is an array of bytes. In my code, everything works fine until I get to the 97th string that I want to parse I get a segmentation fault. I realized that in the 97th string, the bytes read in from my file are blank, despite fread() returning 1024 bytes as being read. However, even though the bytes read appear to be blank, when I write all of the bytes read immediately to a file, the file turns out fine. How can I fix parsing my string when the last token is blank? here is how I am parsing my string:

void test(){
 struct packetNode *ptr = head;
 char *tokens;


 int s, c, size;
 int i = 0;
 char data[1024];

  while(ptr != NULL){
    memset(&data[0], 0, sizeof(data));
    tokens = strtok(ptr->packet,";");
    s = atoi(tokens);
    tokens = strtok(NULL, ";");
    c =  atoi(tokens);
    tokens = strtok(NULL, ";");
    size = atoi(tokens);
    tokens = strtok(NULL, ";");
    strcpy(data, tokens);

    printf("sequence: %d, checksum: %d, size: %d\n", s,c,size);

    ptr = ptr->next;
   i++;
  }


}

and this is where I am creating the strings:

 //populate initial window of size 100
    FILE *fpNew = fopen("test.jpg", "w");

    for(i = 0; i < 100; i++){
      memset(&data[0], 0, sizeof(data));
      struct packetNode *p; // create packet node
      p = (struct packetNode *)malloc(sizeof(struct packetNode));
      bytes = fread(data, 1, sizeof(data), fp); // read 1024 bytes from file into data buffer
       int b = fwrite(data, 1, bytes, fpNew);

      printf("read: %d\n", bytes);
      memset(&p->packet[0], 0, sizeof(p->packet));
      sprintf(p->packet, "%d;%d;%d;%s", s, 0, numPackets, data); // create packet

      //calculate checksum
      int check = checksum8(p->packet, sizeof(p->packet));
      sprintf(p->packet, "%d;%d;%d;%s", s, check, numPackets, data); //put checksum in packet
      s++; //incremenet sequence number



      if(i == 0){
            head = p;
            tail = p;
            tail->next = NULL;
        }
        else{
            tail->next = p;
            tail = p;
            tail->next = NULL;
        }


    }
  fclose(fp);

At the time you call strcpy, tokens points to a location within data.

This is not allowed; you need to use memmove or anther function call instead.

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