2013-12-09 64 views
0

我正在開發一個C項目。正因爲如此,我們有一個健康重要的閱讀計劃。我可以添加患者並添加讀數並移除患者。其餘所有工作,其中我將鏈接我的代碼。我在removePatient中遇到了一個設置錯誤。我試過gdb,但由於某種原因,它不想今天與我合作。C指針Segfaults

這裏是有問題的代碼:

void removePatient(int patientID) { 
    int i, count; 
    Chartptr patientsChart; 
    Chartptr previousChart; 
    Chartptr currentChart; 
    CBuffptr healthTypeBuffer; 
    CBuffptr allHealthTypeBuffers[MAXREADINGS]; 

    // if patient was found, remove the patient 
    patientsChart = getChart(patientID); 
    if (patientsChart != NULL) { 
     healthTypeBuffer = patientsChart->buffer; 

     if (healthTypeBuffer != NULL) { 
      // gather all the heath type buffers 
      count = 0; 
      for (i = 0; i < MAXREADINGS || healthTypeBuffer != NULL; ++i) { 
       allHealthTypeBuffers[i] = healthTypeBuffer; 
       healthTypeBuffer = healthTypeBuffer->next; 
       count++; 
      } 

      // free all the health type buffers 
      for (i = 0; i < count; ++i) { 
       free(allHealthTypeBuffers[i]); 
      } 
     } 

     // find the chart before specified patient chart 
     currentChart = patientList; 
     while (currentChart != patientsChart) { 
      previousChart = currentChart; 
      currentChart = currentChart->next; 
     } 

     // reorganize list, then free patient chart 
     previousChart->next = patientsChart->next; 
     free(patientsChart); 
    } 
} 

我相信我寫的代碼是相當可讀。

下面是一些在上面的代碼中使用的結構聲明:

/* One health type reading: timestamp + actual value */ 
typedef struct{ 
    char timestamp[MAXTIME+1]; 
    int value; 
}Element; 

/* 
* Health type readings: linked list of Circular buffers 
*/ 
typedef struct healthEntry* CBuffptr; /* pointer to a CircularBuffer */ 

typedef struct healthEntry{ 
    int type;    /* health data type (1-5) */ 
    int start;     /* index of oldest reading */ 
    int end;    /* index of most current reading */ 
    Element reading[MAXREADINGS]; /* fixed array of readings */ 
    CBuffptr next;    /* pointer to next health type buffer */ 
}CircularBuffer; 

/* 
* Patient's health chart: ID + linked list of health type readings 
*/ 
typedef struct chartEntry* Chartptr; /* pointer to a Chart */ 

typedef struct chartEntry{ 
    int id;    /* patient ID */ 
    CBuffptr buffer;  /* pointer to first health type buffer */ 
    Chartptr next;   /* pointer to next patient */ 
}Chart; 

/* global declaration for start of the patient chart linked list */ 
extern Chartptr patientList; 
+1

這是相當多的代碼。您是否嘗試過取出部件並嘗試用代碼的子集複製問題?你是否在編寫時不時進行編譯,並且瞭解何時引入了錯誤?這種信息可以幫助人們幫助你 - 坦率地說,如果你注意到了這些信息,你甚至可以自己解決問題 – cHao

+0

其他所有工作都是100%。唯一添加的代碼是removePatient函數。 – user3043594

+0

[SSCCE](http://sscce.org/)非常有幫助。 – starrify

回答

4

雖然我沒有經過大部分代碼看,下面一行看似可疑的對我說:

for (i = 0; i < MAXREADINGS || healthTypeBuffer != NULL; ++i) { 

我懷疑你希望它是:

for (i = 0; i < MAXREADINGS && healthTypeBuffer != NULL; ++i) { 

可能有其他的問題也一樣,但我PRET確保上面的邏輯至少要求&&

+0

Boo,哈哈cHao先回答:)非常感謝你圖圖 – user3043594