简体   繁体   English

strtok()在C中给出分段错误

[英]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. 在我的代码中,一切正常,直到我到达要解析的第97个字符串,但出现分段错误。 I realized that in the 97th string, the bytes read in from my file are blank, despite fread() returning 1024 bytes as being read. 我意识到在第97个字符串中,尽管fread()返回读取的1024个字节,但从文件读取的字节为空白。 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. 在调用strcpy时,令牌指向数据中的位置。

This is not allowed; 这是不允许的; you need to use memmove or anther function call instead. 您需要改用memmove或anther函数调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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