簡體   English   中英

C 代碼 - 分段錯誤

[英]C code - segmentation fault

我正在嘗試編譯我的 c 代碼,但在執行我的程序后總是出現分段錯誤。 這是我的代碼的一部分:

LINE_LENGTH=300

struct clip {
  int views;
  char *user;
  char *id;
  char *title;
  char *duration;
  struct clip *next;
} *head;

我的主要功能,其中 argv[1] 是我的 csv 文件

int main(int argc, char **argv) {
   int n;
   head = build_a_lst(*(argv+1));
   return 0;}

我的其余代碼

struct clip *build_a_lst(char *fn) {
  FILE *fp;
  struct clip *hp;
  char *fields[5];
  char line[LINE_LENGTH];
  int cnt=0,i;
  hp=NULL;

  fp=fopen(fn,"r");
  if(fp=NULL)
    exit(EXIT_FAILURE);
  while(fgets(line,LINE_LENGTH,fp)!=NULL){
    split_line(fields,line);//fields has five values stored
    hp=append(hp,fields);
    for(i=0;i<5;i++){
      free(fields[i]);
      fields[i]=NULL;
    }
  }

  return hp;
}


void split_line(char **fields,char *line) {
  int i=0;
  char *token, *delim;
  delim = ",\n";

  token=strtok(line,delim);//ok line
  for(;token!=NULL;i++){

    fields[i]=malloc(strlen(token)+1);
    strcpy(fields[i],token);
    token=strtok(NULL,delim);
  }

}

struct clip *append(struct clip *hp,char **five) {
  struct clip *cp,*tp;

  tp=malloc(sizeof(struct clip));
  tp->views=atoi(five[1]);

  tp->user=malloc(strlen(five[0]+1));
  tp->duration=malloc(strlen(five[2]+1));
  tp->id=malloc(strlen(five[3]+1));
  tp->title=malloc(strlen(five[4]+1));

  strcpy(tp->user,five[0]);
  strcpy(tp->duration,five[2]);
  strcpy(tp->id,five[3]);
  strcpy(tp->title,five[4]);

  cp=hp;
  while(cp!=NULL)
    cp=cp->next;

  cp->next=tp;
  hp=cp;

  return hp;
}

根據一些文章,分段錯誤是由試圖讀取或寫入非法內存位置引起的。 由於我在代碼的不同部分分配內存,問題應該就在那里。 有人可以幫我解決這個問題。 先感謝您。

您的代碼存在一些問題:

  1. if(fp=NULL)應該是if(fp == NULL)
  2. char *fields[5]; 應該是char *fields[5] = {NULL};
  3. for(;token!=NULL;i++){應該是for(; token != NULL && i < 5; i++){
  4. 這些:

     tp->user=malloc(strlen(five[0]+1)); tp->duration=malloc(strlen(five[2]+1)); tp->id=malloc(strlen(five[3]+1)); tp->title=malloc(strlen(five[4]+1));

    應該

    tp -> user = malloc(strlen(five[0]) + 1); tp -> duration = malloc(strlen(five[2]) + 1); tp -> id = malloc(strlen(five[3]) + 1); tp -> title = malloc(strlen(five[4]) + 1);
  5. 您不會free幾個malloc ed 內存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM