繁体   English   中英

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

[英]Segmentation Fault, when assigning member variable

出于某种原因,当我尝试将成员变量分配给存储在向量结构中的值时,我遇到了分段错误。 如果我注释掉该分配,分段错误就会消失。

它发生的位置在下方并标有星号。 如果有帮助,可以在下面指向我的 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 上的项目代码

我发现了这个错误。 在将任何内容推送到 fragList 之前,我试图从 fragList 中的元素获取值。 我只是使用了一个 if 语句来确保它不是空的。 抱歉,我刚刚开始编程,但我非常感谢反馈并帮助我到达这里。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM