0

我过去使用 strdup() 的方式与在这里使用它的方式相同。我将 token2 传递给 strdup,它的类型为 char *,其中有一个有效的指针,但是当我尝试运行“name = strdup(token2);”行时 我的程序段错误,我很不确定为什么。如果有人能够帮助我,将不胜感激。我也意识到我的代码还没有返回正确的类型,我仍在努力编写所有代码。

struct YelpDataBST* create_business_bst(const char* businesses_path, const char* reviews_path){

  if(fopen(businesses_path,"r") == NULL || fopen(reviews_path,"r") == NULL)
    return NULL;
  FILE* fp_bp = fopen(businesses_path, "r");
  FILE* fp_rp = fopen(reviews_path, "r");

  struct YelpDataBST* yelp = malloc(sizeof(struct YelpDataBST*));

  int ID = -1;
  int tempID;
  long int addressOffset;
  long int reviewOffset;
  char line[2000];
  char line2[2000];
  char temp[2000];
  char temp2[2000];
  char* token;
  char* token2;
  char* name;
  int len;

  BusList* busNode = NULL;
  BusList* busList = NULL;
  BusTree* busTreeNode = NULL;
  BusTree* busTree = NULL;

  ID = -1;
  tempID = 0;
  fgets(line,2000,fp_rp);
  fgets(line2,2000,fp_bp);
  fseek(fp_rp,0, SEEK_SET);
  fseek(fp_bp,0,SEEK_SET);
  int ct = 0;
  while(!feof(fp_rp)){

     len = strlen(line);
     token = strtok(line, "\t");
     //printf("line: %s\n", line);
     token2 = strtok(line2, "\t");
     tempID = atoi((char*)strdup(token));
     if(ct == 0){
       tempID = 1;
       ct++;
     }

  if((ID != tempID || (ID < 0)) && tempID != 0){
    if(tempID == 1)
      tempID = 0;
    token2 = strtok(NULL, "\t");
    //name = strdup(token2);
    reviewOffset = ftell(fp_rp);
    if(tempID != 0)
      reviewOffset -= len;
    addressOffset = ftell(fp_bp);
    ID = atoi((char*)strdup(token));
    busList = BusNode_insert(busList, addressOffset, reviewOffset); //replace with create node for tree
    token2 = strtok(NULL, "\t");
    token2 = strtok(NULL, "\t");
    token2 = strtok(NULL, "\t");
    token2 = strtok(NULL, "\t");
    token2 = strtok(NULL, "\t");
    token2 = strtok(NULL, "\n");
    fgets(line2,2000,fp_bp);
  }
  token = strtok(NULL, "\t");
  token = strtok(NULL, "\t");
  token = strtok(NULL, "\t");
  token = strtok(NULL, "\t");
  token = strtok(NULL, "\n");
  fgets(line,2000,fp_rp);

  } 

  //BusList_print(busList);

}
4

1 回答 1

0

strdup(token)段错误很可能通过token为 NULL 来解释。(无论如何,你不需要在这里strdup)。将该段代码更改为:

if ( token == NULL )
{
    fprintf(stderr, "Invalid data in file.\n");
    exit(EXIT_FAILURE);  // or some other error handling
}

tempID = atoi(token);

然而,周围代码的一个更大问题是您试图一次使用strtok两次。它保持内部状态,您在任何时候都只能有一个strtok“正在进行”。第二个取消第一个。您将不得不重新设计那部分代码。


此外,while(!feof(fp_rp)) 是错误的,并且您的yelpmalloc 的字节数错误(尽管在发布的代码中,您实际上从未尝试在该存储中存储任何内容,因此它还不会导致错误)。

于 2014-11-24T00:01:39.230 回答