簡體   English   中英

C快速排序結構會導致分段錯誤

[英]C quick sort of a struct causes segmentation fault

該程序正在從文件中逐行讀取並將信息存儲在結構中。 除對結構數組排序外,其他所有操作均有效。 例如,最后,當我打印struct(末尾包含的代碼)時,它可以正常工作。

當我調用qsort時出現問題(分段錯誤)。

另外,打印students [0] .lastName可以正常工作,但是打印students [1] .lastName返回一個(空),這也很令人困惑。

我到處都看過了,我的代碼似乎與作為正確的排序結構解決方案發布的代碼非常相似,所以我很困惑。

在main標頭中定義結構:

// DEFINE STRUCT
typedef struct _StudentInformation  {
    int term;
    int studentId;
    char *lastName;
    char *firstName;
    char *subject;
    int catalogNumber;
    char *section;
} StudentInformation;

在主要方法中分配結構(STUDENT_DATA = 50):

// ALLOCATE AN ARRAY OF STUDENTS (STRUCT)
    StudentInformation *students;
    if ((students = malloc(STUDENT_DATA*sizeof(StudentInformation)))==NULL) {
        scanf("Error can't allocate enough students!\n");
        exit(1);
}

問題:調用quicksort(之所以使用8,是因為有8個條目可以正常工作並被加載,甚至少於8個也不起作用):

qsort(students, 8, sizeof(StudentInformation), comparator);

快速排序比較器:

int comparator (const void * a, const void * b) {
    StudentInformation *s1 = (StudentInformation*)a;
    StudentInformation *s2 = (StudentInformation*)b;

    return strcmp(s1->lastName, s2->lastName);
}

我知道數據可以很好地加載是因為打印完全正常:

void printInformation (StudentInformation *students) {
    // PRINT EVERYTHING
        while(students->firstName!=NULL) {
            printf("%-s, %s %15d %4d %4s%d %7s\n",
                    students->lastName,students->firstName,students->term,
                    students->studentId, students->subject,students->catalogNumber,
                    students->section);

            // Increment
            students=students+sizeof(StudentInformation);
        }
}

它打印的內容(我只打印了8個中的2個,不打印NULL):

Castille, Michael Jr            1201 103993269  CSE230     R03
Boatswain, Michael R.            1201 105515018  CSE230     R01

謝謝!

該行:

if ((students = malloc(STUDENT_DATA*sizeof(StudentInformation)))==NULL)

為結構本身分配內存,但不為指針引用的字符串分配內存:

char *lastName;
char *firstName;
char *subject;
char *section;

這些中的每一個都占用足夠的內存來存儲指針。 您需要分別為字符串分配內存:

if ((lastName = malloc((LAST_NAME_LEN + 1) * sizeof(char))) == NULL) {
  // Error
}
if ((firstName = ...

編寫不屬於您的內存始終是調試ricochet-errors上意外課程的好方法:您最終可能會遇到segfault或內存損壞,但似乎在代碼領域完全與問題的實際來源無關。

如果STUDENT_DATA> = 8,則只有一種可能的解釋,那就是您的一個或多個lastName字段從未被初始化,並且包含NULL或垃圾。 如果初始化這些字段的循環包含與打印循環相同的錯誤(使用students=students+sizeof(StudentInformation)而不是students++ ),這就是原因。

您說Calling quicksort (the reason for the 8 is because there are 8 entries

這是不正確的。 您應該傳遞數組中的元素數(在您的情況下為STUDENT_DATA )。

暫無
暫無

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

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