0

次のコードで「セグメンテーション違反(コアダンプ)」ランタイムエラーが発生します。

#include <iostream>
#include "Student.h"
#include "SortedList.h"

using namespace std;

#define BOUNDS 100

int main() {

    SortedList *list = new SortedList();  // points to the sorted list object
    Student *create[BOUNDS];  // array to hold 100 student objects
    int num = 100000;   // holds different ID numbers

    // fills an array with 100 students of various ID numbers
    for (int i = 0; i < BOUNDS; i++) {
        create[i] = new Student(num);
        num += 10;
    }

    // insert all students into the sorted list
    for (int i = 0; i < BOUNDS; i++)
    list->insert(create[i]);

    // individually deletes each student
    num = 100000;
    for (int i = 0; i < BOUNDS; i++) {
        delete list->find(num);
    num += 10;
    }

    // insert all students into the sorted list
    for (int i = 0; i < BOUNDS; i++)
    list->insert(create[i]);

    num = 100000;
    for (int i = 0; i < BOUNDS; i++) {
    list->remove(num);
    num += 10;
    }

    cout << "test2" << endl;
    delete list;
    return 0;
}

delete list;エラーを行(または最初に来る方)に絞り込みました。私はこれがなぜであり、おそらくそれを修正する方法について疑問に思っています。この問題に関する洞察は役に立ちます。

4

5 に答える 5

1

私が見ることができる2つの問題があります。

まず、このループで:

for (int i = 0; i < BOUNDS; i++) {
    x = new Student(num);
    num += 10;
}

一連の dynamic を作成しStudent、最新のものを入れるxと、前のものは失われます。これにより、100 個Studentの s が動的に作成され、そのうち 99 個がリークされます。Studentまた、上記のコメントのように配列を sで埋めません。ここで何をしようとしているのかわからないので、代わりに何をする必要があるかについてコメントすることはできません.

次に、deleteここで呼び出しています。

delete list->find(num);

Student自動ストレージ (スタック) にある s (自動 s を保持する s へのポインターでリストを埋めたため) 、Studentこれは未定義の動作につながり、おそらく segfault の原因です。の最後で配列が範囲外になると割り当てが解除されるため、これらの s の割り当てを解除する必要はありません。createStudentStudentmain

于 2012-04-11T23:32:24.050 に答える
0

どのように実装されているかを知らずStudentListに、これは一種の暗いショットですが...

list->insert(&create[i]);スタック割り当てオブジェクトをリストに追加し、このスタック割り当てdelete list->find(num);オブジェクトの削除を試みます。割り当てられたオブジェクトをスタックすることはできません。delete

これに加えて、最初のforループでメモリ リークが発生しています。

そして、私は忍者になりました。

于 2012-04-11T23:33:12.273 に答える
0

この行には問題があります:

list->insert(&create[i]);

その時点で、createは割り当てられていますが、何も入れられていません。おそらく の結果がx = new Student(num)そこに割り当てられるはずです。

于 2012-04-11T23:33:58.503 に答える
0

「create」配列はスタックに割り当てられます。スタックに割り当てられたメモリを削除しようとしているため、このエラーが発生します。

リストを削除->find(num);

于 2012-04-11T23:39:20.760 に答える
0

あなたは間違いなくメモリをリークしています:

// fills an array with 100 students of various ID numbers
for (int i = 0; i < BOUNDS; i++) {
    x = new Student(num);
    num += 10;
}

このスニペットでは、ポインターを追跡できる場所にxctor が魔法のように自分自身を挿入しない限り、リークが発生します。Student

そして、それはクラッシュに関連している可能性があります。

于 2012-04-11T23:30:51.983 に答える