分配成员变量时出现分段错误

Segmentation Fault, when assigning member variable

本文关键字:分段 错误 成员 变量 分配      更新时间:2023-10-16

由于某种原因,当我试图将成员变量分配给存储在向量结构中的值时,我得到了分段错误。如果我注释掉这个赋值,分割错误就消失了。

发生的位置在下面,用星号标记。如果有帮助的话,可以在下面的github链接上找到我的代码的其余部分。

void LinkedList::findFragments(){
    //Initialize variables
currentNode = head;
prevNode = head;
int fragListSize = 0;
vector<fragment> tempVec;
bool f = false;
fragment temp;
int arr[32];
//Find all the fragment groups
//Put all the isFree flags into an array
for(int i = 0; i < 32; i++){
    arr[i] = currentNode->isFree;
    currentNode = currentNode->next;
}
//Find Groups of 1's which show open fragments of memory
for (int i = 0; i < 32; i++) {
        if (!f && arr[i] == 1) {
                f = true;
                temp.begin = i;
        }
        if (f && arr[i] == 0) {
                f = false;
                temp.end = i - 1;
                temp.size = temp.end - temp.begin + 1;
                tempVec.push_back(temp);
        }
        if (f && i == 31) {
                f = false;
                temp.end = i;
                temp.size = temp.end - temp.begin + 1;
                tempVec.push_back(temp);
        }
}
//Make fragList equal to tempVec
fragList = tempVec;
//Sorting the fragments by size
fragListSize = fragList.size();
for(int j = 0; j < fragListSize; j++){
    for(int i = 0; i < fragListSize- j - 1; i++){
        if(fragList[i].size < fragList[i + 1].size){
            iter_swap(fragList.begin() + i, fragList.begin() + i + 1);
        }
    }
}
cout << "test 3" <<endl;
int max, min;
//Find the min and max sizes of the fragments
max =0;
for(int i = 0; i < fragListSize;i++)
{
    if(fragList[i].size > fragList[max].size)
    {
        max = i;
    }
}
min =0;
for(int i = 0; i < fragListSize;i++)
{
    if(fragList[i].size < fragList[min].size)
    {
        min = i;
    }
}
    for(int i =0; i< fragListSize; i++){
        cout << "Begin index: " << fragList[i].begin << " End index: "
                << fragList[i].end<< "Frag Size"<< fragList[i].size << endl;
    }
//Set largest and smallest Fragment size
//********************Segmentation Fault********************
largestFragment = fragList[max].size;
smallestFragment = fragList[min].size;
//Set the position of the smallest and largest fragments
largestFragmentPos = max;
smallestFragmentPos = min;
}

GitHub项目代码

我发现了这个bug。在任何东西被推送到fragList之前,我试图从fragList的元素中获得一个值。我只是使用了if语句来确保它不是空的。很抱歉,我刚刚开始编程,但我真的很感谢你的反馈和帮助。